How to change the background color of rows in a GridView in ASP.NET 3.5



In this article we will learn how to change the background color of the rows in a GridView control based on its row data using RowDataBound event

Introduction:

This article explains 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

DataBound1.gif

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

<connectionStrings>

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

</connectionStrings>

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

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

<asp:SqlDataSource
            ID="sqlProduct"
            runat="server"
            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

        <asp:GridView
            ID="grdProduct"
            runat="server"
            DataSourceID="sqlProduct"
            OnRowDataBound="grdProduct_RowDataBound">
            </asp:GridView>

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.

Result:

DataBound.gif

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


Similar Articles