How to verify if a DataGridViewCheckBoxCell is Checked

前端 未结 7 1590
小鲜肉
小鲜肉 2021-01-11 10:45

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

相关标签:
7条回答
  • 2021-01-11 11:39

    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
    
    0 讨论(0)
提交回复
热议问题