如何通过CheckBoxList循环并插入如果选中Box

时间:2012-11-22 14:47:27

标签: c# asp.net sql ado.net

我想循环此代码并保存选定的CheckBoxList项。我该怎么办?

String insCmd = "Insert into Sale (Name, price) values (@Name, @price)";
SqlCommand insertUser = new SqlCommand(insCmd, myConnection);
insertUser.Parameters.AddWithValue("@Name", CheckBoxList1.SelectedItem.ToString());
insertUser.Parameters.AddWithValue("@price", Convert.ToDecimal(TextBox3.Text));

try
{
  myConnection.Open();
  insertUser.ExecuteNonQuery();
  myConnection.Close();
}
catch (Exception er)
{
  Response.Write("<script>alert('Error While Input')</script>");
}

3 个答案:

答案 0 :(得分:4)

connection.Open()
var insertUser = new SqlCommand(insCmd, connection);   

foreach(var item in CheckBoxList1.Items)
{
  if(!item.Selected) continue;
  insertUser.Parameters.Clear();
  // your code where you can use Item.Text to add parameters
  // i have no idea about your textboxes though 
  insertUser.ExecuteNonQuery();
}
connection.Close();

但这不是最佳方式。最佳方式将涉及表值参数和存储过程。

答案 1 :(得分:1)

您可以使用LINQ迭代所选项目。

using (var con = new SqlConnection())
{
    try
    {
        con.Open();
        const string query = "INSERT INTO Sale (Name, Price) VALUES (@Name, @Price)";
        using (var command = new SqlCommand(query, con))
        {
            foreach (var item in CheckBoxList1.Items.Cast<ListItem>().Where(item => item.Selected))
            {
                command.Parameters.Clear();
                command.Parameters.AddWithValue("@Name", item.Text);
                command.Parameters.AddWithValue("@Price", Convert.ToDecimal(TextBox3.Text));
                command.ExecuteNonQuery();
            }
        }
        con.Close();
    }
    catch (Exception)
    {
        Response.Write("<script>alert('Error While Input')</script>");
    }
}

答案 2 :(得分:0)

        var items = new System.Collections.ArrayList(checkedListBox1.CheckedItems);
        foreach (var item in items)
        {
            //your function for saving
        }

或者,重做你的插入函数,传递所选事物的集合,并将你的插入与你检查的所有值连接起来并用1执行查询去使其更快/更有效