17

我是编程和 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”类型的操作数。

4

6 回答 6

38

您应该使用Convert.ToBoolean()检查是否选中了 dataGridView 复选框。

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
         }
    }
}
于 2014-03-25T13:14:41.667 回答
6

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

因此,为了让那些偶然发现这个问题的人明白这一点,

实现 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!
        }  
    }              
}
于 2016-03-09T14:15:57.627 回答
4

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

if ((bool)row.Cells[1].Value == true)
{
    // what I want to do
}
于 2013-12-08T11:25:00.343 回答
1
if (Convert.ToBoolean(row.Cells[1].EditedFormattedValue))
{
    //Is Checked
}
于 2017-07-18T15:32:51.860 回答
0

上面这段代码是错误的!

foreach (DataGridViewRow row in dataGridView1.Rows)
{
    DataGridViewCheckBoxCell cell = row.Cells[0] as DataGridViewCheckBoxCell; 

    // Note: Can't check cell.value for null if Cell is null 
    // just check cell != null first
    //We don't want a null exception!
    if (cell.Value != null)
    {
        if (cell.Value == cell.TrueValue)
        {
           //It's checked!
        }  
    }              
}
于 2020-12-04T20:38:37.200 回答
0

稍微修改一下就可以了

if (row.Cells[1].Value == (row.Cells[1].Value=true))
{
    // what I want to do
}
于 2017-02-11T21:32:39.420 回答