Click here to Skip to main content
15,913,300 members
Please Sign up or sign in to vote.
3.67/5 (2 votes)
See more:
I have 10 rows in datagrid view and I use VS2010.
How can I change a backcolor of odd and even rows different?
I try my best but I have one error that is:
Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index

My code is in vb.net(windows form) as follows:

VB
Dim CountR As Integer
CountR = 0
While CountR <= DataGridView1.RowCount          
  If CountR Mod 2 = 0 Then
    DataGridView2.Rows(CountR).DefaultCellStyle.BackColor = Color.Pink
  Else
    DataGridView2.Rows(CountR).DefaultCellStyle.BackColor = Color.SkyBlue
  End If
  CountR = CountR + 1
End While
Posted
Updated 13-Sep-17 2:59am
v2
Comments
JF2015 11-Dec-10 12:35pm    
Edited to improve spelling and code formatting.

C#
for (int i = 0; i < GridView1.Rows.Count; i++)
                {
                    if (GridView1.Rows.Count % 2 == 0)
                    {
                        e.Row.Cells[0].BackColor = System.Drawing.Color.Green;
                        e.Row.Cells[1].BackColor = System.Drawing.Color.Green;
                       //here e.Row.Cells[1] from own database
                    }
                    else
                    {
                        e.Row.Cells[0].BackColor = System.Drawing.Color.Red;
                        e.Row.Cells[0].BackColor = System.Drawing.Color.Red;
                  
                    }

                }
 
Share this answer
 
Comments
Deepu S Nair 28-Jan-15 2:02am    
Answering old questions adds nothing to the previous solution and is likely to attract
downvoting.
The DataGridView has properties AlternatingRowsDefaultCellStyle and RowsDefaultCellStyle.

Look them up on MSDN or the web and you'll find lots of examples.

Good luck. :)
 
Share this answer
 
Check the DataGridView properties
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900