Sag*_*ran 2 .net c# datagridview nullreferenceexception winforms
我正在使用winforms和C#.

当我尝试获取datagridviewcheckbox状态时,如果复选框不为true,则显示"Null Reference Exception被捕获"为异常.
我的代码是
foreach (DataGridViewRow fees_row in this.dataGridView2.Rows)
{
if ((bool) fees_row.Cells[0].Value == true)
{
}
}
Run Code Online (Sandbox Code Playgroud)
错误在于:
if ((bool) fees_row.Cells[0].Value == true)
Run Code Online (Sandbox Code Playgroud)
如何设置datagridview复选框值不为null.或者逃避这个例外.
在尝试询问其值之前,您需要确保该DataGridViewCell对象不是null 第一个.这就是导致你正在NullReferenceException审讯对象Value属性的原因null!
将代码更改为如下所示:
foreach (DataGridViewRow fees_row in this.dataGridView2.Rows)
{
var cell = fees_row.Cells[0];
if (cell != null)
{
var value = cell.Value;
if (value != null && (bool)value == true)
{
// Do whatever...
}
}
}
Run Code Online (Sandbox Code Playgroud)
但在其他人留下一个讽刺的评论之前,通常没有理由针对文字检查布尔值true.你要写的就是if (boolValue)
| 归档时间: |
|
| 查看次数: |
6368 次 |
| 最近记录: |