2012-02-16 70 views
0

我试图捕捉复选框列的单元格的状态在一个DataGridView(启用/禁用)在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
//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; 
} 
+0

工作就像一个魅力,谢谢! – globetrotter 2012-02-16 16:11:19

相关问题