如何检查dataGridView checkBox是否被选中?

我是编程和C#语言的新手。 我卡住了,请帮忙。 所以我编写了这段代码(c#Visual Studio 2012):

private void button2_Click(object sender, EventArgs e) { foreach (DataGridViewRow row in dataGridView1.Rows) { if (row.Cells[1].Value == true) { // what I want to do } } } 

所以我得到以下错误:

运算符’==’不能应用于’object’和’bool’类型的操作数。

您应该使用Convert.ToBoolean()来检查是否已选中dataGridView checkBox。

 private void button2_Click(object sender, EventArgs e) { foreach (DataGridViewRow row in dataGridView1.Rows) { if (Convert.ToBoolean(row.Cells[1].Value)) { // what you want to do } } } 

值返回对象类型,无法与布尔值进行比较。 您可以将值转换为bool

 if ((bool)row.Cells[1].Value == true) { // what I want to do } 

这里的所有答案都容易出错,

因此,要清除那些偶然发现这个问题的人,

实现OP所需要的最佳方法是使用以下代码:

 foreach (DataGridViewRow row in dataGridView1.Rows) { DataGridViewCheckBoxCell cell = row.Cells[0] as DataGridViewCheckBoxCell; //We don't want a null exception! if (cell.Value != null) { if (cell.Value == cell.TrueValue) { //It's checked! } } } 

稍作修改应该有效

 if (row.Cells[1].Value == (row.Cells[1].Value=true)) { // what I want to do } 
 if (Convert.ToBoolean(row.Cells[1].EditedFormattedValue)) { //Is Checked }