How to verify if a DataGridViewCheckBoxCell is Checked

自古美人都是妖i 提交于 2019-12-30 08:09:48

问题


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

回答1:


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:

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



回答2:


Thank you all. Had the same problem but i find out that writing senderGrid.EndEdit(), before checking the value, resolves it.

private void dgvRiscos_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        var senderGrid = (DataGridView)sender;
        senderGrid.EndEdit();

        if (senderGrid.Columns[e.ColumnIndex] is DataGridViewCheckBoxColumn &&
            e.RowIndex >= 0)
        {

            var cbxCell = (DataGridViewCheckBoxCell)senderGrid.Rows[e.RowIndex].Cells["associado"];
            if ((bool)cbxCell.Value)
            {
                   // Criar registo na base de dados
            }
            else
            {
                   // Remover registo da base de dados
            }
        }
    }

Keep up the good work




回答3:


 if (Convert.ToBoolean(dgvScan.Rows[rowIndex].Cells["Status"].Value))
{
//Do Something
}
else {
// Do Something
}



回答4:


Another issue that may be encountered is this:

When the user clicks the cell to check or uncheck the box, the underlying value will not be changed until the cell loses focus.

This will not be an issue if the code in question is in a button, since the cell will lose focus when you click the button. But if your code is fired from a timer, you may still be checking the 'old' value.

See my other answer here: https://stackoverflow.com/a/22080846/1015072




回答5:


I have no prior experience in this, but I guess you should check the value of the column or property.

Try to have a look to this example:

http://programmingwithstyle.blogspot.com/2007/06/how-to-get-from-datagridviewcheckboxcel.html




回答6:


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
}



回答7:


bool checked = cell.Value as bool? ??  false;


来源:https://stackoverflow.com/questions/1563190/how-to-verify-if-a-datagridviewcheckboxcell-is-checked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!