Hi jain4,
Here i have created sample. Refer the below code.
HTML
<asp:DropDownCheckBoxes ID="DropDownCheckBoxes1" runat="server" UseSelectAllNode="false">
<Style SelectBoxWidth="195" DropDownBoxBoxWidth="160" DropDownBoxBoxHeight="90" />
</asp:DropDownCheckBoxes>
<asp:ExtendedRequiredFieldValidator ID="ExtendedRequiredFieldValidator1" runat="server"
ControlToValidate="DropDownCheckBoxes1" ErrorMessage="Required" ForeColor="Red"></asp:ExtendedRequiredFieldValidator>
<br />
<br />
<asp:Button Text="Submit" runat="server" OnClick="Submit" />
Code
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.PopulateCountries();
}
}
private void PopulateCountries()
{
using (SqlConnection con = new SqlConnection(constr))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Countries"))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
DropDownCheckBoxes1.DataSource = cmd.ExecuteReader();
DropDownCheckBoxes1.DataTextField = "CountryName";
DropDownCheckBoxes1.DataValueField = "CountryId";
DropDownCheckBoxes1.DataBind();
}
con.Close();
}
}
protected void Submit(object sender, EventArgs e)
{
foreach (ListItem item in DropDownCheckBoxes1.Items)
{
if (item.Selected)
{
InsertprdCountry("10", item.Text.Trim(), item.Value.Trim());
}
}
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "alert('Record inserted successfully.');", true);
}
protected void InsertprdCountry(string prdID,string countryName,string CountryId)
{
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO prdCountries (prdID, countryName, CountryId) values (@prdID, @countryName, @CountryId)"))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@prdID", prdID);
cmd.Parameters.AddWithValue("@countryName", countryName);
cmd.Parameters.AddWithValue("@CountryId", CountryId);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
Screenshot
