如何知道是否选中了表单中的多个复选框并将其插入数据库表C#中

问题描述

我想在数据库表中为每个复选框(如果选中则为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();

        

我想像下面那样在数据库表中的一行中插入日期

  • (第一数据表行=第二数据库表列)

  • (第二个数据表行=第三个数据库表列)

  • (第三数据表行=第四数据库表列)

并且我确保表行等于复选框的数量

以及如何对所有第一行列执行以下反向过程。

  • 如果表中的第二列为1,则将第一个复选框更改为选中状态
  • 如果表中的第二列为0,请将第一个复选框更改为未选中

一直到列末。

解决方法

您可以创建一个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");
        }
    }          
}

这是因为我不知道您的数据库表中还有什么其他内容,如果您将这些列添加到问题中,则可以更新答案。