Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 296
Stonep123 Avatar asked Oct 06 '12 17:10

Stonep123


2 Answers

Check that CurrentCell.RowIndex isn't the header row index.

like image 36
Steve Wellens Avatar answered Oct 11 '22 21:10

Steve Wellens


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());   
}
like image 52
Saurabh R S Avatar answered Oct 11 '22 22:10

Saurabh R S