问题描述
我想在数据库表中为每个复选框(如果选中则为1,未选中的为0)插入值。
我将所有复选框都放在了一个组框中。
sqlConnection conn = new sqlConnection(@"Data Source =.\sqlEXPRESS; Initial Catalog = sales_sys;
Integrated Security = True");
sqlCommand cmd = new sqlCommand();
cmd.Connection = conn;
cmd.CommandText = /* insert sql statement*/ ;
int x =0;
DataTable tbl = new DataTable();
tbl.Clear();
tbl.Columns.Add("value");
foreach (Control c in groupBox1.Controls)
{
if (c is CheckBox)
{
CheckBox cb = (CheckBox)c;
if (cb.Checked == false)
{ x = 0 ;}
else
{ x = 1;}
tbl.Rows.Add(1);
int index = tbl.rows.count - 1;
tbl.rows[index][0] = x;
}
conn.open();
tb.Load(cmd.ExecuteReader());
conn.Close();
我想像下面那样在数据库表中的一行中插入日期
并且我确保表行等于复选框的数量
以及如何对所有第一行列执行以下反向过程。
一直到列末。
解决方法
您可以创建一个checkedlistbox
mychecked列表,然后使用
private void savemychecks()
{
DataTable tbl = new DataTable();
tbl.Clear();
tbl.Columns.Add("value");
foreach (object item in mycheckedlist.Items)
{
if (mycheckedlist.CheckedItems.Contains(item))
{
tbl.Rows.Add("1");
}
else
{
tbl.Rows.Add("0");
}
}
}
这是因为我不知道您的数据库表中还有什么其他内容,如果您将这些列添加到问题中,则可以更新答案。