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++;

 

        }

 

    }

Published Monday, October 12, 2009 1:04 AM by nijhawan.saurabh

Comments

# re: Setting AlterNateRow BackColor For Two Rows At A Time In GridView

Monday, October 12, 2009 12:50 PM by RichardD

A simpler option would be:

int count = 0;

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

{

   if (4 == count) count = 0;

   if (0 == count || 1 == count)

   {

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

   }

   else

   {

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

   }

}

# re: Setting AlterNateRow BackColor For Two Rows At A Time In GridView

Tuesday, October 13, 2009 6:39 AM by nijhawan.saurabh

Hey Thanks RichardD.

A nice alternative.

Leave a Comment

(required) 
(required) 
(optional)
(required)