Search code examples
c#datagridviewcell

datagridview cell click event


I have an event for a cell click in a datagrid view to display the data in the clicked cell in a message box. I have it set to where it only works for a certain 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 any of the column headers, a blank messagebox shows up. I cant figure out why, any tips?


Solution

  • You will also need to check the cell clicked is not the 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());   
    }