Quantcast
Viewing all articles
Browse latest Browse all 10

ASP.NET C# Change GridView Cell Background Color Based on Value

On of the useful things you can do with GridViews in ASP.NET is to run code during the rendering of each individual row. This allows you to change aspects, such as visual appearance, of each row based on the values of the cells. For instance, you can change the background color of the cell based on the value:

Image may be NSFW.
Clik here to view.

To accomplish this, you simply need to add a function to the “RowDataBound” attribute of the GridView.

GridView1.RowDataBound += new GridViewRowEventHandler(GridView1_RowDataBound);

void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
	if (e.Row.RowType == DataControlRowType.DataRow)
	{
		int value = (int)DataBinder.Eval(e.Row.DataItem, e.Row.Cells[2].Text); 
		// e.Row.Cells[2] references the cell value you want to use
		if (value < 100)
		{
			e.Row.Cells[2].BackColor = Color.FromName("#c6efce");
		}
		if ((value >= 100) && (value < 500))
		{
			e.Row.Cells[2].BackColor = Color.FromName("#ffeb9c");
		}
		if (value >= 500)
		{
			e.Row.Cells[2].BackColor = Color.FromName("#ffc7ce");
		}
	}
}

In this example, I took the value of the 3rd cell of the row (“e.Row.Cells[2]”) and changed the background color of the cell based on the value.


Viewing all articles
Browse latest Browse all 10

Trending Articles