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();
}
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.
In some cases, you may also need to test whether the rowindex and columnindex go beyond the limits of the backing data.