This code will be used to determine wheter a cell value (from a datagridview) is 0, if so it's background color will be red.
int countRows = dataGridView1.Rows.Count;
for (int i = 0; i < countRows + 1; i++)
if (int.Parse(dataGridView1.Rows[i].Cells.Value.ToString()) == 0)
dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Red;
But i get a NullReferenceException at the red marked line.
So i have two questions:
1. How can i fix this?
2. Is it possible to get data from a cell by using it's columnname? Not like dataGridView1.Rows[i].Cells.Value.ToString() since the database column places can be changed.
Thanks in advance.
You're trying to access a row that doesn't exist. Remove the "+1" in the loop, then read up on which indices are valid in an array.
I removed the +1 and i went through the loop with a messagebox to check if i would get the values i want and i did.
So i don't know how to check what's wrong.
Fixed it, the +1 had to be -1
Then you're not including the last row...
Originally Posted by Chronik
May I suggest using enumerators to traverse the rows instead? Then you don't need to fiddle with indices.
foreach(System.Web.UI:WebControls.GridViewRow Row in dataGridView1.Rows)
if (int.Parse(Row.Cells.Value.ToString()) == 0)
Row.DefaultCellStyle.BackColor = Color.Red;