In this post I will explain how we can insert the multiple selected value of Checkbox list into database.
Description:
I have created table name QUALIFICATION. ID is primary key.
ID
|
int
|
CANDIDATE_QUALIFICATION
|
varchar(50)
|
Now go to Visual Studio and take new website. After that add a webform to application. Drag and drop Checkboxlist control from Toolbox.
<asp:CheckBoxList ID="chkeducation" runat="server">
<asp:ListItem>M.SC.</asp:ListItem>
<asp:ListItem>MBA</asp:ListItem>
<asp:ListItem>B.TECH</asp:ListItem>
<asp:ListItem>MCA</asp:ListItem>
<asp:ListItem>B.SC.</asp:ListItem>
<asp:ListItem>POST GRADUATION</asp:ListItem>
</asp:CheckBoxList>
<br />
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Insert" />
Code Behind:
Add namespace.
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
SqlConnection con = newSqlConnection(ConfigurationManager.ConnectionStrings["connection"].ToString());
protected void Page_Load(object sender, EventArgs e)
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
String str = "";
for (int i = 0; i <= chkeducation.Items.Count - 1; i++)
{
if (chkeducation.Items[i].Selected)
{
if (str == "")
{
str = chkeducation.Items[i].Text;
}
else
{
str += "," + chkeducation.Items[i].Text;
}
}
}
con.Open();
SqlCommand cmd = new SqlCommand("Insert into QUALIFICATION(CANDIDATE_QUALIFICATION) values('" + str + "')", con);
cmd.ExecuteNonQuery();
Clear();
}
public void Clear()
{
chkeducation.SelectedIndex = -1;
}
No comments:
Post a Comment