首页 > 解决方案 > C#删除数据库中所有选中的复选框

问题描述

我在删除数据库中选中的复选框时遇到问题。表明

字符串未被识别为有效的布尔值

在这条线上:

if (bool.Parse(item.Cells[0].Value.ToString()))

这是我检查所有复选框的代码

 if (checkBox2.Checked == false)
        {
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0];
                chk.Value = chk.TrueValue;

            }
        }
        else if (checkBox2.Checked == true)
        {
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0];
                chk.Value = 1;

                if (row.IsNewRow)
                {
                    chk.Value = 0;
                }
            }
        }

//这是我将选中的复选框删除到数据库的代码。

int count = 0;
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            if ((Convert.ToBoolean(row.Cells[0].Value) == true))
            {
                count++;
            }
        }

        if (count == 0)
        {
            MessageBox.Show("Please select an item to delete");
        }
        else
        {

            foreach (DataGridViewRow item in dataGridView1.Rows)
            {
                if (bool.Parse(item.Cells[0].Value.ToString()))
                {

                    connection.Close();
                    connection.Open();
                    SqlCommand cmd = new SqlCommand();
                    cmd.Connection = connection;

                    cmd.CommandText = "INSERT INTO tbl_Archive ([ID],[Date],[StartTime],[EndTime],[NameOfSchool],[Pax],[TourAgency],[Coordinator],[ContactNumber],[Date & Time Added]) VALUES ('"
                    + id + "','" + myDate + "','" + start + "','" + end + "','" + school + "','" + pax + "','" + touragency + "','" + coordinator + "','" + contact + "','" + dateadded + "')";
                    cmd.ExecuteNonQuery();
                    cmd.CommandText = "DELETE FROM tbl_Schedule WHERE [ID] = '" + item.Cells[1].Value.ToString() + "'";
                    cmd.ExecuteNonQuery();
                    cmd.CommandText = "DELETE FROM tbl_ScheduledVisitors WHERE [ID] = '" + item.Cells[1].Value.ToString() + "'";
                    cmd.ExecuteNonQuery();
                    connection.Close();

                }

            }
            MessageBox.Show("Successfully Deleted");
            refreshgrid();
            checkBox2.Checked = false;

            //}
        }

错误

标签: c#sql-server

解决方案


为了诊断问题,您可以在这两行设置断点:

if ((Convert.ToBoolean(row.Cells[0].Value) == true))

if (bool.Parse(item.Cells[0].Value.ToString()))

看看它的价值item.Cells[0].Value是多少。

它很可能不是有效的布尔字符串。


推荐阅读