How to verify if a DataGridViewCheckBoxCell is Che

2019-02-16 11:51发布

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

7条回答
在下西门庆
2楼-- · 2019-02-16 12:34

CbxCell.Value must be equal to DBNull.Value (your column can contain null values right?)

I would check for DBNull before casting:

if (!DBNull.Value.Equals(CbxCell.Value) && (bool)CbxCell.Value == true)
{
    //Do stuff
}
else
{
    //Do Stuff
}
查看更多
登录 后发表回答