1

我正在使用带有复选框的下拉菜单,我可以在其中选择多个项目,并且我正在使用它将数据插入到我的详细信息视图中。我的问题是,如果我从下拉列表中选择了多个项目,即使我从下拉框中选择了多个项目,它也只会插入第一个被选中的项目。我在这里做错了什么?请。帮助

 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();
            }

        }
    }
4

1 回答 1

1

首先,您应该使用 ListBox 的SelectedItems属性,它为您提供所有选定项目的集合(然后您可以获取它们的值)。这比手动浏览所有项目更容易。

您的代码中的问题是您使用 的SelectedValue属性cblCustomerList,而您应该使用 的Value属性listItem

尝试这个:

protected void DetailsView1_ItemInserting(object sender, DetailsViewInsertEventArgs e)
{

    foreach (ListItem listItem in cblCustomerList.Items)
    {
        if (listItem.Selected)
        {

            string GroupName = listItem.Value; // fix is here


        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();
        }

    }
}
于 2012-12-13T03:06:08.557 回答