In Excel, there is a useful feature that lets you change the color of a cell depending on its value. As example, you could make a “total money” cell show up with a red background if its value is below zero. How can we do this with ASP.NET gridviews? There is no built-in functionality to make this work, you’ll need to write a few lines of code to get this done. Here is how I would solve this issue: Subscribe to the RowDataBound Event of your gridview, it is fired when the current row has been bound to data (filled with values):
GridView gv = new GridView();
gv.RowDataBound += new GridViewRowEventHandler(gv_RowDataBound);
In the according event handler, iterate through all cells and update their background-color based on their value:
// color last cell
void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.Cells.Count > 0)
{
TableCell c = e.Row.Cells[e.Row.Cells.Count - 1];
if (!string.IsNullOrEmpty(c.Text))
{
try
{
int value = int.Parse(c.Text);
c.BackColor =
value >= 100 ? Color.LimeGreen :
value >= 85 ? Color.Gold :
Color.IndianRed;
c.Text = string.Format(“{0}%”, value); // add percentage sign
}
catch
{
c.Text = null;
}
}
}
}
}
Done…
Recent Comments