【问题标题】:How to handle null exception in dataGridView1_SelectionChanged event?如何处理 dataGridView1_SelectionChanged 事件中的空异常?
【发布时间】:2014-12-12 14:20:05
【问题描述】:

我在dataGridView1_SelectionChanged 事件中收到以下错误。对于第一个选择,它可以工作,但如果我更改选择,我会收到错误:

System.NullReferenceException 未处理
Message=对象引用未设置为对象的实例。

我的代码如下。请纠正我犯错的地方:

private void dataGridView1_SelectionChanged(object sender, EventArgs e)
    {
        int rowindex;
        // MessageBox.Show(dataGridView1.CurrentRow.Index.ToString());
        rowindex = dataGridView1.CurrentRow.Index;   //error        
        if (rowindex >= 0)
        {
            DataGridViewRow row = this.dataGridView1.Rows[rowindex];
            txtpaX.Text = row.Cells["X"].Value.ToString();
            txtpaY.Text = row.Cells["Y"].Value.ToString();
            lblinfo.Text = row.Cells["item"].Value.ToString();

            xposition = int.Parse(txtpaX.Text);
            yposition = int.Parse(txtpaY.Text);
            flag = 1;
        }
    }

【问题讨论】:

  • 在运行时这个事件在初始化期间调用,同时你的数据网格是空的。您可以做的是在表单加载事件的末尾放置一个标志,以将表单的初始化与其他方法和事件区分开来。然后用那个标志设置一个覆盖这个事件的条件。
  • 这听起来很可疑,很不清楚您究竟是如何更改选择的。请记住,您可能隐藏了一个更大的错误,从工作线程更新绑定 DGV 上的数据源可能会破坏 DGV 的内部状态,也会导致此错误。

标签: c# winforms nullreferenceexception


【解决方案1】:

试试

   if (dataGridView1.CurrentRow != null)
   {

   }

另外,您在设置.Text 属性时需要检查空引用,否则您可能会遇到空引用异常。

所以最终的代码看起来像......

private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
    if (dataGridView1.CurrentRow != null)
    {
        int rowindex = dataGridView1.CurrentRow.Index;
        if (rowindex >= 0)
        {
            DataGridViewRow row = dataGridView1.Rows[rowindex];
            if (row.Cells["X"].Value != null) txtpaX.Text = row.Cells["X"].Value.ToString();
            if (row.Cells["Y"].Value != null) txtpaY.Text = row.Cells["Y"].Value.ToString();
            if (row.Cells["item"].Value != null) lblinfo.Text = row.Cells["item"].Value.ToString();

            xposition = int.Parse(txtpaX.Text);
            yposition = int.Parse(txtpaY.Text);
            flag = 1;
        }
    }
}

【讨论】:

    猜你喜欢
    • 2011-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-13
    • 2019-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多