如何遍历的CheckBoxList,如果复选框被选中插入 [英] How to Loop Through CheckBoxList and insert if Box is checked

查看:376
本文介绍了如何遍历的CheckBoxList,如果复选框被选中插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想这个循环code和保存选定的CheckBoxList项目。我应该怎么办呢?

 字符串insCmd =INSERT INTO出售(名称,价格)值(@Name,@price);
SqlCommand的insertUser =新的SqlCommand(insCmd,MyConnection的);
insertUser.Parameters.AddWithValue(@名称,CheckBoxList1.SelectedItem.ToString());
insertUser.Parameters.AddWithValue(@价格,Convert.ToDecimal(TextBox3.Text));

尝试
{
  myConnection.Open();
  insertUser.ExecuteNonQuery();
  myConnection.Close();
}
赶上(例外ER)
{
  回复于(<脚本>警报(错误而输入)LT; / SCRIPT>中);
}
 

解决方案

  connection.Open()
VAR insertUser =新的SqlCommand(insCmd,连接);

的foreach(在CheckBoxList1.Items VAR项)
{
  如果继续(item.Selected!);
  insertUser.Parameters.Clear();
  //你的code,您可以使用Item.Text添加参数
  //我不知道你的文本框,虽然
  insertUser.ExecuteNonQuery();
}
的Connection.close();
 

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

I would like to loop this code and save selected CheckBoxList items. How should I do it?

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

解决方案

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

But this is not the optimal way. Optimal way will involve table valued parameters and stored procedures.

这篇关于如何遍历的CheckBoxList,如果复选框被选中插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆