Ohad
Ohad

Reputation: 17

How to change Gridview's row color based on a specific cell value? Asp.net

I browsed through dozens of websites and posts now and I can't find anything "right".

All I want is to paint a row with a red color in my Datatable/GridView based on specific cell value.

Please help me out here :( . . .

for (int i = 0; i < TheFinalTable.Rows.Count; i++)
        {
            TheLevel = myUsers[i, 0];

            if (TheLevel == "2" && TheFinalTable.Rows[i][4].ToString() == myUsers[i, 1])
            {
                Gridview1.Rows[i].ForeColor = System.Drawing.Color.LightGreen;
            }
            if (TheLevel == "3" && TheFinalTable.Rows[i][4].ToString() == myUsers[i, 1])
            {
                Gridview1.Rows[i].ForeColor = System.Drawing.Color.Red;

            }
        }

"MyUsers" is a string array that contains The level and the ID.

            Level  |  id

       1  |   2       64


       2  |   3       23

"TheFinalTable" contains The following in this order: Mail, Name, Lastname, phone, ID, Rent, LastLog.


Just noticed it also says "Index was out of range" when it comes to the second if (which it is true).

The main question is this:

How to set different color to a specific row based on the row's one cell value or just by the row number?

Hope to hear from you guys soon.

Take care.

Upvotes: 0

Views: 3776

Answers (1)

CodingYoshi
CodingYoshi

Reputation: 27009

Subscribe to the RowDataBound event of the grid in your page's load method:

this.GridView1.RowDataBound += GridView1_RowDataBound; 

Whenever the row is bound to the data, it will call your handler. Here is the event handler where you will do the changing of the background color:

private void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
   //make sure it is not the header row
   if(e.Row.RowType == DataControlRowType.DataRow)
   {
      // whatever your condition
      if(e.Row.Cells[0].Text == "Whatever")
      {
         e.Row.BackColor = Drawing.Color.Red // This will make row back color red
      }
   }
}

Upvotes: 1

Related Questions