c# - 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;
//}
}
解决方案
为了诊断问题,您可以在这两行设置断点:
if ((Convert.ToBoolean(row.Cells[0].Value) == true))
和
if (bool.Parse(item.Cells[0].Value.ToString()))
看看它的价值item.Cells[0].Value
是多少。
它很可能不是有效的布尔字符串。
推荐阅读
- c++ - 为什么 C++17 中基于范围的“for”循环规范发生了变化?
- python-3.x - RuntimeError:使用深度马尔可夫模型时键入“元组”
- sql - 修剪访问列的字符串中的所有额外空格
- javascript - 在 GO 中通过 http 请求检索网站 DOM
- php - $_SERVER['DOCUMENT_ROOT'] 在重写规则后返回不同的值
- sql - 查询获取不包含任何项目集合的行
- r - 如何使mapdeck中的色阶静态
- visual-studio-2017 - 需要有关使用和发布 rdlc 文件的帮助
- sql - Sqlite 中的 IF ELSE 解决方法
- python - 在一个笔记本中使用 tensorflow 和 numpy 时:内核似乎已经死了。它会自动重启