我无法删除数据库中选中的复选框。 它显示
字符串未被识别为有效的布尔值
在此行:
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;
//}
}
答案 0 :(得分:2)
为了诊断问题,可以在以下两行放置断点:
if ((Convert.ToBoolean(row.Cells[0].Value) == true))
和
if (bool.Parse(item.Cells[0].Value.ToString()))
,然后查看item.Cells[0].Value
的值是什么。
这可能不是有效的布尔字符串。
答案 1 :(得分:0)
您可以替换以下内容:
if (bool.Parse(item.Cells[0].Value.ToString()))
与此:
if (Convert.ToBoolean(item.Cells[0].Value))