如何找出datagridview的复选框值时停止空引用异常? [英] How to stop null reference exception when finding datagridview checkbox value?

查看:116
本文介绍了如何找出datagridview的复选框值时停止空引用异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的WinForms和C#,.

I am using winforms and C#,.

当我试图让datagridviewcheckbox状态,如果该复选框不正确显示空引用异常被抓为例外。

When i try to get datagridviewcheckbox state, if the checkbox not true it shows "Null Reference Exception was caught" as Exception.

我的code是

foreach (DataGridViewRow fees_row in this.dataGridView2.Rows)
{
    if ((bool) fees_row.Cells[0].Value == true)
    {
    }
}

该错误是在该行:

The error is in the line:

if ((bool) fees_row.Cells[0].Value == true)

如何设置datagridview的复选框值不为空。或者逃避这种例外。

how to set datagridview checkbox value not null. or escape this exception.

推荐答案

您需要确保该的DataGridViewCell 的对象不是第一的,试图询问它的价值了。那是什么导致了的NullReferenceException -you're询问的该属性对象!

You need to make sure that the DataGridViewCell object is not null first, before trying to interrogate its value. That's what's causing the NullReferenceException—you're interrogating the Value property of a null object!

更改code看起来是这样的:

Change your code to look like this:

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

但在此之前别人留下一个表露无疑评论,但通常不建议对文字来检查一个布尔值。你所编写的如果(boolValue)

But before someone else leaves a snarky comment, there's generally no reason to check a Boolean value against a literal true. All you have to write is if (boolValue)

这篇关于如何找出datagridview的复选框值时停止空引用异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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