如何验证是否DataGridViewCheckBoxCell被选中 [英] How to verify if a DataGridViewCheckBoxCell is Checked

查看:475
本文介绍了如何验证是否DataGridViewCheckBoxCell被选中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已绑定一个数据表到 DataGridView的,这个数据表有一个名为状态列是类型布尔。我可以将值设置为真正通过代码就好了。



不过,我无法弄清楚如何检查,看看是否给定的行已经被选中。这是我想使用和编译它显示错误指定的强制转换无效的代码。



任何帮助,将不胜感激。

 如果(rowIndex位置> = 0)
{
VAR cbxCell =(DataGridViewCheckBoxCell)dgvScan.Rows [rowIndex位置] .Cells [ 状态];

如果((布尔)cbxCell.Value)
{
//做的东西
}
,否则
{
/ /做其他的东西
}
}


解决方案

问题是,对于一个DataGridCheckBoxColumn默认FALSE值为null,并且默认TRUE值为True布尔值。这会导致一个问题,因为布尔值不为空。你能解决这个问题的方法有两种:!



 如果(cbxCell.Value = NULL&放大器;及(布尔)cbxCell.Value )
{
做的东西;
}



另一种方式来解决这个设置列的TrueValue属性一些值。这可以在设计时进行,如下所示:





然后,你可以写:

 如果((字符串)cbxCell.Value ==T)
{
做的东西;
}

这工作,因为字符串是空。



请注意:即使我设置FalseValue为f假值似乎仍然是空的,所以我建议忽略了FalseValue财产



另一个注意:如果你把东西TrueValue如上然后学尝试删除它,真值变为零(哎哟),requireing您删除列,然后才能将其恢复到初始状态重新添加它。或者你可以在代码如下更改:



 ((DataGridViewCheckBoxColumn)DataGridView1.Columns [选择])TrueValue =真正的


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

解决方案

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

这篇关于如何验证是否DataGridViewCheckBoxCell被选中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆