I assume it works for every row except 0?
When I worked with DataGridViews I noticed that sometimes there are some strange problems when you use SelectedRows property.
Also DGW sort of creates cells "on the fly", I don't really understand the mechanism behind it, but sometimes some clells aren't accessible. Although, I never experienced this problem in CellContentClic k event.
If you're using CellContentClic k event, you may want to get the row you clicked this way:
- private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
-
{
-
if (e.RowIndex>-1 && e.ColumnIndex>-1) // it's row header and column header, trying to access it may cause errors
-
{
-
string id, name, price, desc, quan;
-
id = Convert.ToString(dataGridView1.Rows[e.RowIndex].Cells[0].Value);
-
name = Convert.ToString(dataGridView1.SelectedRows[e.RowIndex].Cells[1].Value);
-
price = Convert.ToString(dataGridView1.SelectedRows[e.RowIndex].Cells[2].Value);
-
desc = Convert.ToString(dataGridView1.SelectedRows[e.RowIndex].Cells[3].Value);
-
quan = Convert.ToString(dataGridView1.SelectedRows[e.RowIndex].Cells[4].Value);
-
txtID.Text = id;
-
txtName.Text = name;
-
txtPrice.Text = price;
-
txtDesc.Text = desc;
-
txtQuan.Text = quan;
-
}
-
}
Also, had you tried using column names instead fo indexes when you select the cell?
You may also want to check if what you're accessing exist:
- object value = DataGridView1.Rows[rowindex].Cells[columnindex].Value;
-
if (value is DBNull) { return; }