2012-10-06 48 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());