0

我想循环这段代码并保存选定的 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>");
}
4

3 回答 3

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

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

于 2012-11-22T14:58:50.437 回答
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>");
    }
}
于 2012-11-22T19:00:08.700 回答
0
        var items = new System.Collections.ArrayList(checkedListBox1.CheckedItems);
        foreach (var item in items)
        {
            //your function for saving
        }

或者,重做您的插入功能,传递所选事物的集合,并将您的插入与您检查的所有值连接起来,并使用 1 go 执行查询以使其更快/更高效

于 2012-11-22T15:24:16.677 回答