如何验证DataGridViewCheckBoxCell是否被检查 [英] How to verify if a DataGridViewCheckBoxCell is Checked
问题描述
我已经将一个数据表绑定到一个 DataGridView
,这个数据表有一个名为Status的列,类型为$ code> Boolean 。我可以通过代码将值设置为 true
或 false
。
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".
任何帮助将不胜感激。
if (rowIndex >= 0)
{
var cbxCell = (DataGridViewCheckBoxCell)dgvScan.Rows[rowIndex].Cells["Status"];
if ((bool)cbxCell.Value)
{
// Do stuff
}
else
{
// Do other stuff
}
}
推荐答案
问题是DataGridCheckBoxColumn的默认FALSE值为null,默认TRUE值为布尔值True。这会导致一个问题,因为布尔值不可为空。您可以通过两种方式解决这个问题:
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;
}
另一种解决方法是将列的TrueValue属性设置为某些值。这可以在设计时完成,如图所示:
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:
然后你可以写:
if ((string)cbxCell.Value == "T")
{
do stuff;
}
这是因为字符串可以空。
This works because Strings are nullable.
请注意:即使我将FalseValue设置为F,假值仍然为null,因此我建议忽略FalseValue属性。
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.
另外一个注意事项:如果你像上面那样把一些东西放在TrueValue中,然后尝试擦除它,True值将变为null(ouch),需要你删除列,然后重新添加它,以便将它恢复到默认条件。或者您可以按照以下代码更改代码:
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
这篇关于如何验证DataGridViewCheckBoxCell是否被检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!