dataGridView复选框列“对象引用未设置为对象的实例”

时间:2012-02-16 12:41:20

标签: winforms c#-4.0

我正在尝试捕获Windows窗体的dataGridView_CellEndEdit事件中dataGridView(启用/禁用)中复选框列的单元格状态,如下所示:

 private void dataGridView2_CellEndEdit(object sender, DataGridViewCellEventArgs e)
 {
    if (e.ColumnIndex == 2)
       { 
          switch ((bool)dataGridView2.Rows[e.RowIndex].Cells[2].Value)
               {
                 case true:
                    //do something
                    break;
                 case false:
                    //do something else
                    break;
                 default:
                    break;
               }
       }
  }

这与一个案件有所不同;当我单击复选框单元格的任何部分而不是白色矩形(例如我错过了),然后尝试单击其他内容时,我收到此错误:“对象引用未设置为对象的实例。”此行发生此错误:

switch ((bool)dataGridView2.Rows[e.RowIndex].Cells[2].Value)

我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

//put before the switch 
if (e.RowIndex<0 || dataGridView2.Rows[e.RowIndex] ==null || dataGridView2.Rows[e.RowIndex].Cells[2].Value ==null )
{
//cannot determine what was selected , you could return or do something else . . .
return;
}