将多个listdownms的dropdownlist插入到数据库的多行中

时间:2015-09-30 05:52:47

标签: c# sql asp.net bootstrap-select

我正在尝试将多个选定的asp.DropdownList值插入到数据库的多行中。我正在使用Silvio Montero bootstrap选择CSS来实现多项选择。

我正在使用foreach()循环来执行此操作,但只有第一个选定的项目才会插入到数据库中。 asp.DropdownList是从另一个数据库填充的。

<asp:ListBox runat="server" CssClass="selectpicker form-control" multiple data-live-search="true" ID="DropDownList1" DataTextField="username" DataValueField="username" >

    </asp:ListBox>

以下是c#代码 -

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindDropDownList();
        }
    }
    private void BindDropDownList()
    {

        using (SqlConnection con = new SqlConnection(CS))

            using (SqlCommand cmd = new SqlCommand("SELECT DISTINCT [username], [email] FROM [Login]", con))
            {
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                da.Fill(ds);

                DropDownList1.DataSource = ds;
                DropDownList1.DataTextField = "username";
                DropDownList1.DataValueField = "username";
                DropDownList1.DataBind();
            }

    }


    protected void sendbutton_Click(object sender, EventArgs e)
    {
        foreach (ListItem item in DropDownList1.Items)
        {

            if (item.Selected)
            {
                using (SqlConnection sqlcon = new SqlConnection(CS))
                {
                    sqlcon.Open();
                    using (SqlCommand cmd = new SqlCommand())
                    {
                        cmd.Connection = sqlcon;
                        cmd.CommandType = CommandType.Text;
                        cmd.CommandText = "INSERT INTO DB (schdlby, schdldate, schdltime, sub, event, participants ) values (@schdlby, @schdldate, @schdltime, @sub, @event, @participants)";
                        cmd.Parameters.AddWithValue("@schdlby", Page.User.Identity.Name.ToString());
                        cmd.Parameters.AddWithValue("@schdldate", cl.SelectedDate.ToShortDateString());
                        cmd.Parameters.AddWithValue("@sub", txtsub.Text);
                        cmd.Parameters.AddWithValue("@schdltime", schdltime.Text.Trim());
                        cmd.Parameters.AddWithValue("@event", txtevent.Text);
                        cmd.Parameters.AddWithValue("@parti", item.Value.ToString());
                        cmd.ExecuteNonQuery();

// Code to send automated SMTP mail to each dropdown selection

}
                }
            }      
        }

        Response.Redirect("Second.aspx");
    }

编辑:我刚刚发现它在asp:CheckBoxList中有效但在使用asp:ListBox时不起作用

0 个答案:

没有答案