Odd/Even datagridview rows background color
There is a DataGridView
alternate row view style option in the forms designer. AlternatingRowsDefaultCellStyle
in the properties grid
You are getting exception because you are accessing row that is not present. GridView rows are zero based index
, it means if you have ten rows in grid the index will be from 0 to 9 and you should iterate one less then the rows count
. The i <= dataGridView1.Rows.Count
will give exception on last iteration because when count is 10 (total rows are ten) and dataGridView1.Rows[10] does not exists therefore exception is thrown.
Change <= in loop condition to <
for (int i = 0; i <= dataGridView1.Rows.Count ; i++)
To
for (int i = 0; i < dataGridView1.Rows.Count ; i++)
You Should AlternatingRowsDefaultCellStyle property to set alternative row style to keep it simple and efficient.