Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Odd/Even datagridview rows background color

I have datagridview and now I would like to change background color of its each row depending whether row number is even or odd.

I thought that there must be easier way to reach that. Then using for example this part of code and modify it so it would change the colours of dtg's row. If this snippet of code is one of the ways to do that, may someone help me to improve it so it wouldn't throw exception when index is out if rabge?

public void bg_dtg()
    {
        try
        {

            for (int i = 0; i <= dataGridView1.Rows.Count ; i++)
            {
                if (IsOdd(i))
                {

                    dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.LightBlue;
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(""+ex);
        }
    }

   public static bool IsOdd(int value)
   {
       return value % 2 != 0;
   }

Thank you for your time and answers.

like image 909
Marek Avatar asked Aug 19 '13 10:08

Marek


1 Answers

There is a DataGridView alternate row view style option in the forms designer. AlternatingRowsDefaultCellStyle in the properties grid

like image 143
Colin Steel Avatar answered Sep 19 '22 01:09

Colin Steel