Datagridview cell click event

I have an event for a cell click in a datagrid view to display data in a cell with a click in the message box. I found that it only works for a specific column and only if there is data in the cell

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

however, whenever I click on any of the column headings, a blank message appears. I can’t understand why, any advice?

+4
source share
5 answers

You will also need to verify that the cell clicked is not a column header cell. Like this:

 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()); } 
+16
source

Verify that CurrentCell.RowIndex not a header row index.

+2
source
 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
source

The decision made throws an exception "an object that is not installed in the instance of the object", because checking the null reference MUST occur before checking the actual value of the variable.

 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()); } 
+1
source

try it

  if(dataGridView1.Rows.Count > 0) if (dataGridView1.CurrentCell.ColumnIndex == 3) MessageBox.Show(dataGridView1.CurrentCell.Value.ToString()); 
0
source

Source: https://habr.com/ru/post/1438179/


All Articles