How to verify if a DataGridViewCheckBoxCell is Checked

user189442 picture user189442 · Oct 14, 2009 · Viewed 37.9k times · Source

I have bound a data table to a DataGridView, this data table has a column called "Status" which is of type Boolean. I can set the value to true or false just fine via code.

However, I can't figure out how to check to see if the given row is already checked or not. This is the code I am trying to use and compiling it shows the error "the specified cast is invalid".

Any help would be appreciated.

if (rowIndex >= 0)
{
    var cbxCell = (DataGridViewCheckBoxCell)dgvScan.Rows[rowIndex].Cells["Status"];

    if ((bool)cbxCell.Value)
    {
        // Do stuff
    }
    else
    {
        // Do other stuff
    }
}

Answer

Mark Ainsworth picture Mark Ainsworth · Jan 7, 2014

The problem is that the default FALSE value for a DataGridCheckBoxColumn is null, and the Default TRUE value is the boolean value True. This causes a problem because boolean values are not nullable. You can solve this problem two ways:

    if (cbxCell.Value != null && (bool)cbxCell.Value)
    {
        do stuff;
    }

The other way to solve this is set the TrueValue property of the column to some value. This can be done at design time as shown:

enter image description here

Then you can write:

    if ((string)cbxCell.Value == "T")
    {
        do stuff;
    }

This works because Strings are nullable.

Please note: Even though I set the FalseValue to be F the false value still seems to be null, so I suggest ignoring the FalseValue property.

One other note: IF you put something in TrueValue as above and then attemp to erase it, True value becomes null (ouch), requireing you to delete the column and then re-add it in order to restore it to the default condition. Or you can change it in code as follows:

((DataGridViewCheckBoxColumn)DataGridView1.Columns["Selected"]).TrueValue = true