Tuesday 31 March 2009

Rendering Different Colors for each row in an ASP.NET Gridview

This is simple as handling the MyGridViewName_RowDataBound event. The following code sample is used in the following scenario:
  1. The grid is bound to a LINQDataSource (the e.Row.DataItem has a type of "DynamicClass" and so cannot be cast directly)
  2. Consequently uses reflection to get a nested property inside the e.Row.DataItem, then casts that to a known LINQ2SQL class.
  3. From this reflected information, grabs the display colour HEX value (e.g. #CCFFCC and converts it to a System.Drawing.Color colour (by using System.Drawing.ColorTranslator).

protected void proposalListGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DoPBusiness.PlanningProposalTracking.PP_LIST_Status status =
(DoPBusiness.PlanningProposalTracking.PP_LIST_Status)
e.Row.DataItem.GetType()
.GetProperty("PP_LIST_Status")
.GetValue(e.Row.DataItem, null);

e.Row.BackColor = System.Drawing.ColorTranslator.FromHtml(status.DisplayColour);
}
}




NB. An alternative (and preferred) to using relection to get the nested property is using LINQ projection - which is how I did it when I checked the code into source. control. However, the code sample above still illustrates the topic of this post.

No comments: