How to check if dataGridView checkBox is checked?

2019-02-16 18:43发布

I'm new to programming and C# language. I got stuck, please help. So I have written this code (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'.

5条回答
放我归山
2楼-- · 2019-02-16 18:57

You should use Convert.ToBoolean() to check if dataGridView checkBox is checked.

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
         }
    }
}
查看更多
smile是对你的礼貌
3楼-- · 2019-02-16 19:04

Slight modification should work

if (row.Cells[1].Value == (row.Cells[1].Value=true))
{
    // what I want to do
}
查看更多
Root(大扎)
4楼-- · 2019-02-16 19:05

Value return an object type and that cannot be compared to a boolean value. You can cast the value to bool

if ((bool)row.Cells[1].Value == true)
{
    // what I want to do
}
查看更多
甜甜的少女心
5楼-- · 2019-02-16 19:10
if (Convert.ToBoolean(row.Cells[1].EditedFormattedValue))
{
    //Is Checked
}
查看更多
可以哭但决不认输i
6楼-- · 2019-02-16 19:12

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:

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!
        }  
    }              
}
查看更多
登录 后发表回答