简体   繁体   中英

How to check if dataGridView checkBox is checked?

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'.

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

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

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
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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