2012-10-06 95 views
4

我有一个单元格单击DataGrid视图中的事件以显示消息框中单击单元格中的数据。我有它设置为它仅适用于某一列且仅当有数据在小区datagridview单元格单击事件

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) 
{ 
    if (dataGridView1.CurrentCell.ColumnIndex.Equals(3)) 
     if (dataGridView1.CurrentCell != null && dataGridView1.CurrentCell.Value != null) 
      MessageBox.Show(dataGridView1.CurrentCell.Value.ToString()); 
} 

然而,每当我点击任何列标题,一个空白消息框显示出来。我无法弄清楚为什么,有什么提示?

回答

16

您还需要检查单击的单元格不是列标题单元格。就像这样:

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) 
{ 
    if (dataGridView1.CurrentCell.ColumnIndex.Equals(3) && e.RowIndex != -1){ 
     if (dataGridView1.CurrentCell != null && dataGridView1.CurrentCell.Value != null) 
      MessageBox.Show(dataGridView1.CurrentCell.Value.ToString()); 
} 
+0

谢谢这个伟大的工作 – Stonep123

+0

只需注意你应该第一个条件之前检查'dataGridView1.CurrentCell!= NULL'... – MatanKri

2

检查CurrentCell.RowIndex是否不是标题行索引。

1
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) 
{  
    if (e.RowIndex == -1) return; //check if row index is not selected 
     if (dataGridView1.CurrentCell.ColumnIndex.Equals(3)) 
      if (dataGridView1.CurrentCell != null && dataGridView1.CurrentCell.Value != null) 
       MessageBox.Show(dataGridView1.CurrentCell.Value.ToString()); 
} 
1

接受的解决方案抛出“对象不设置到对象的实例”异常为空引用检查必须检查变量的实际值之前发生。

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) 
{  
    if (dataGridView1.CurrentCell == null || 
     dataGridView1.CurrentCell.Value == null || 
     e.RowIndex == -1) return; 
    if (dataGridView1.CurrentCell.ColumnIndex.Equals(3)) 
     MessageBox.Show(dataGridView1.CurrentCell.Value.ToString()); 
} 
0

试试这个

 if(dataGridView1.Rows.Count > 0) 
      if (dataGridView1.CurrentCell.ColumnIndex == 3) 
       MessageBox.Show(dataGridView1.CurrentCell.Value.ToString()); 
相关问题