How to change the background color of rows in a GridView based on the value of a column in ASP.NET 3.5

By | January 27, 2012


This article will explain you how to change the background color of the GridView rows to red if the value of “List Price” field is greater than 1000.

Steps 1: Create a new ASP.NET Web Application

Step 2: Insert a ConnectionString in the Web.config file

<add name="conString" connectionString="Data Source=.\SQL2005Express; User Id=sa; Password=password; Initial Catalog=AdventureWorks"/>

Note: It’s a good practice to add your connection string in the Web.config file. I am using SQL Server 200 Express edition. You can add your own connection string.

 Step 3: Write code for the SQLDataSource in Default.aspx file

    ConnectionString="<%$ConnectionStrings:conString %>"
    SelectCommand="SELECT ProductID, Name, ListPrice FROM Production.Product WHERE ListPrice>0" />

Note: You can drag a SqlDataSource control from the ToolBox and configure its DataSource using Configure Data Source wizard.

Step 4: Write code for the GridView in Default.aspx file


Note: You can drag a GridView and set its properties using Properties Dialog Box.

Step 5: Write code for the RowDataBound event of the GridView

protected void grdProduct_RowDataBound(object sender, GridViewRowEventArgs e)
     if (e.Row.RowType == DataControlRowType.DataRow)
      	Double ListPrice=Double.Parse(e.Row.Cells[2].Text);
        if (ListPrice > 1000)
        	e.Row.BackColor = System.Drawing.Color.Red;

RowDataBound event of the GridView control fires every time a row is bound to data. So this is the best place to access row value before it is displayed in the GridView.

DataControlRowType.DataRow is used here to determine the type of row being bound. Other frequently used properties are Header, Footer and Pager.


Note: I am using AdventureWorks database. Which can be downloaded from here.


0 thoughts on “How to change the background color of rows in a GridView based on the value of a column in ASP.NET 3.5

  1. Akhil gupta


    Using following code i m getting this error

    ‘_Default.GridView1_RowDataBound(object, System.Web.UI.WebControls.GridViewRowEventArgs)’ is inaccessible due to its protection level

  2. Carol

    I like the helpful information you provide in your articles.
    I will bookmark your blog and check again here regularly.
    I am quite sure I will learn many new stuff right here! Best of
    luck for the next!


Leave a Reply

Your email address will not be published. Required fields are marked *