loads of useful information, examples and tutorials pertaining to web development utilizing asp.net, c#, vb, css, xhtml, javascript, sql, xml, ajax and everything else...

 



Advertise Here
C-Sharpener.com - Programming is Easy!  Learn Asp.Net & C# in just days, Guaranteed!

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

by naspinski 2/8/2009 8:42:00 AM

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!

Currently rated 4.5 by 2 people

  • Currently 4.5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

asp.net | css

Related posts


Comments are closed