I am using a drop down with checkbox where i can select more that one item and i am using it to insert the data into my detailview. My issue is that if i select more than one item from the drop down, it only inserts the first item that is selected even though i selected more than one item from the drop down box. What am i doing wrong here? Pls. help
protected void DetailsView1_ItemInserting(object sender, DetailsViewInsertEventArgs e)
{
foreach (ListItem listItem in cblCustomerList.Items)
{
if (listItem.Selected)
{
string GroupName = cblCustomerList.SelectedValue;
sqlcon.Open();
string eno = ((TextBox)DetailsView1.FindControl("txteno")).Text.ToString();
string empname = ((TextBox)DetailsView1.FindControl("txtempname")).Text.ToString();
string sal = ((TextBox)DetailsView1.FindControl("txtsal")).Text.ToString();
SqlCommand cmd = new SqlCommand("select eno from emp where eno = '" + eno + "'", sqlcon);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
lblmsg.Text = "Employee No already exists";
}
else
{
dr.Close();
sqlcmd = new SqlCommand("insert into emp values('" + eno + "', '" + empname + "','" + sal + "' , '" + GroupName + "')", sqlcon);
sqlcmd.ExecuteNonQuery();
// DetailsView1.ChangeMode(DetailsViewMode.Insert);
}
sqlcon.Close();
// LoadDet();
}
}
}
First, you should use the SelectedItems property of the ListBox, which gives you a collection of all selected items (you can then get their values). It’s easier than manually going through all the items.
The issue in your code is that you use the
SelectedValueproperty ofcblCustomerList, while you should use theValueproperty oflistItem.Try this: