Setting AlterNateRow BackColor For Two Rows At A Time In GridView

This was part of a question asked on asp.net forums, i thought of sharing it here as well.

“How can i have first two rows with one color in a GridView and another color for the next two rows and so on.”

 

Here’s The Code:

 

protected void Page_Load(object sender, EventArgs e)

    {

        int count = 0;

        for (int i = 0; i < GridView1.Rows.Count;i+=2 )

        {

            if (count % 2 == 0)

            {

                if (i != GridView1.Rows.Count - 1)

                {

                    int j = i + 1;

                    GridView1.Rows[i].BackColor = System.Drawing.Color.Blue;

                    GridView1.Rows[j].BackColor = System.Drawing.Color.Blue;

                }

                else

                {

                

                    GridView1.Rows[i].BackColor = System.Drawing.Color.Blue;

                }

            }

            else

            {

                if (i != GridView1.Rows.Count - 1)

                {

 

                    int k = i + 1;

                    GridView1.Rows[i].BackColor = System.Drawing.Color.Red;

                    GridView1.Rows[k].BackColor = System.Drawing.Color.Red;

                }

                else

                {

 

                    GridView1.Rows[i].BackColor = System.Drawing.Color.Red;

                }

            }

            count++;

 

        }

 

    }

2 Comments

Comments have been disabled for this content.