DataGridView.CurrentCell.RowIndex属性上出现意外的空引用异常

时间:2013-02-15 17:55:20

标签: c# winforms datagridview nullreferenceexception

DataGridView.CurrentCell属性是否可能不是null且其null属性的值为RowIndex? 如果是这样,我怎么能阻止这个呢?

额外信息: 对SelectionChanged事件DataGridView事件检查此值,以保持当前选定行的索引存储在类字段中。

代码如下:

private void dgTraffic_SelectionChanged(object sender, EventArgs e)
{
    try
    {
        if (dgReport.CurrentCell != null)
            actualRow = dgReport.CurrentCell.RowIndex;
    }
    catch (NullReferenceException ex)
    {
    #if DEBUG
        MessageBox.Show("Error on dgTraffic_SelectionChanged:\n" + ex.Message);
    #endif
    }
}

不知怎的,我在引用RowIndex属性的行上得到了一个未处理的NullReferenceException,所以我添加了try-catch,但我无法弄清楚这是怎么回事。 顺便说一句,我意识到方法名称是“dgTraffic”,方法体中使用的对象读取dgReport。它实际上是这样设置的,这是用于dgReport的SelectionChanged事件的方法。

0 个答案:

没有答案
相关问题