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

July 21st, 2010 | Categories: Code, How To, Web | Tags: , , , ,

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:

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.

  • Share/Bookmark
Print

Facebook Comments

  1. J Morris
    August 6th, 2010 at 10:39
    Reply | Quote | #1

    How would you code the page if you were using a String value in the Column cell?

  2. August 6th, 2010 at 10:43
    Reply | Quote | #2

    string value = DataBinder.Eval(e.Row.DataItem, e.Row.Cells[2].Text);

    if (value == “some string”)
    {

    }

    You might have to add ToString() at the end if it doesn’t work automatically: string value = DataBinder.Eval(e.Row.DataItem, e.Row.Cells[2].Text).ToString();

  3. J Morris
    August 6th, 2010 at 12:43
    Reply | Quote | #3

    Thanks! I will try it out.