简体   繁体   English

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

[英]How to check if dataGridView checkBox is checked?

I'm new to programming and C# language.我是编程和 C# 语言的新手。 I got stuck, please help.我卡住了,请帮忙。 So I have written this code (c# Visual Studio 2012):所以我写了这段代码(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
         }
    }
}

And so I get the following error:所以我收到以下错误:

Operator '==' cannot be applied to operands of type 'object' and 'bool'.运算符“==”不能应用于“object”和“bool”类型的操作数。

You should use Convert.ToBoolean() to check if dataGridView checkBox is checked.您应该使用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
         }
    }
}

All of the answers on here are prone to error,这里的所有答案都容易出错,

So to clear things up for people who stumble across this question,所以为了让那些偶然发现这个问题的人澄清事情,

The best way to achieve what the OP wants is with the following code:实现 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!
        }  
    }              
}

Value return an object type and that cannot be compared to a boolean value.值返回一个对象类型,不能与布尔值进行比较。 You can cast the value to bool您可以将值转换为 bool

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

Slight modification should work稍微修改应该工作

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

This code above was wrong!上面这段代码是错误的!

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!
        }  
    }              
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM