如何在dataGridView1_SelectionChanged事件中处理null异常?

时间:2014-10-17 03:49:28

标签: c# winforms nullreferenceexception

我在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;
        }
    }

1 个答案:

答案 0 :(得分:0)

尝试

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