Mayank Mishra
Mayank Mishra

Reputation: 25

Exception while click on column of the grid

I am working on a datagrid and on cellClick event get data on the relevent texbox for editing. When I click on the row it works fine but when I click on any of the column it gives exception and I dont know why.

Here's my code :

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
    itmId.Text = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
    itmNme.Text = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
    untCst.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
    qntty.Text = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString();
    manfDate.Text = dataGridView1.Rows[e.RowIndex].Cells[4].Value.ToString();
}

Upvotes: 1

Views: 1386

Answers (1)

Ted Spence
Ted Spence

Reputation: 2668

When you click on the header of the table, it sends the row index of -1. There are other instances where this event can fire with invalid rowindex and columnindex values.

You should test rowindex and columnindex before using them.

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) 
{ 
    if (e.RowIndex >= 0 && e.ColumnIndex >= 0) {
        // .. my code goes here ..
    }
}

In some cases, you may also need to test whether the rowindex and columnindex go beyond the limits of the backing data.

Upvotes: 4

Related Questions