Saturday, March 26, 2011

Setting the row background color in a GridView based on a value in the the row

This is something that needs to be done often, but it is not always obvious how to do it

Often times you want a row to be colored different or highlighted based on values, this can be useful for multiple reasons. This is a very simple thing, but not all that obvious.

Make your different CSS classes

Set up some CSS classes that will be used for the row coloring:
.blue { background:Blue; }
.orange { background:Orange; }
.normal { background:Transparent; }

Set your RowDataBound event in your GridView

This is going to happen on the RowDataBound event, so be sure to call one in your GridView:
<asp:Repeater ID="gv" onrowdatabound="gv_RowDataBound" ...

Set up your event to handle the row

Now handle each row in the event:
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
  e.Row.CssClass = e.Row.Cells[0].Text.Equals("1") ? "blue" : "normal";
}

It's just that simple. Now, if the text in Cell[0] (the first cell) of a row is equal to "1" the row will have it's CssClass set to "blue", otherwise it will be "normal".

Now if you want to have multiple different cases:
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
  switch(e.Row.Cells[0].Text)
  {
    case "1" : e.Row.CssClass = "blue"; break;
    case "2" : e.Row.CssClass = "orange"; break;
    default : e.Row.CssClass = "normal"; break;
  }
}

Now if the first cell is equal to "1", it will be blue, if it is equal to "2" is will be orange, or else it will be transparent; so simple! 

No comments:

Post a Comment