Change Rows Background color in GridView with selected Criteria



In this article we change background color of the rows in a GridView with selected criteria on GridView1_RowDataBound event.

GridCriteria1.gif

In aspx page

In an aspx page first add a GridView control then set the SqlDataSource for the GridView to the NorthWind database.

GridCriteria2.gif

In aspx.cs page

In aspx.cs page write the code for the Gridview1_RowDataBound Event. Set the criteria you want for the Gridview Row Backcolor Change. The GridView offers a RowDataBound event that fires once for each row after the row has been created and bound to the corresponding record of data from the data source control. In this article I am changing the row background color when CategoryID == 2; you can use whatever criteria you need to.

protected void Gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            // determine the value of the UnitsInStock field
            int CategoryID = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "CategoryID"));
            if (CategoryID == 2)
                // color the background of the row yellow
                e.Row.BackColor = System.Drawing.Color.Brown;
        }
 
    }


In aspx page

In the aspx page on the GridView set the RowDataBound event in the GridView property. Then, in the RowDataBound line, type in the name of the event handler you want to create (I named my event handler productsGridView_RowDataBound). Finally, enter in the following code into the event handler on OnRowDataBound="Gridview1_RowDataBound" .

GridCriteria3.gif

Conclusion

In this article we try to improve GridView design based on certain criteria. Hopefully it's useful for you.

Up Next
    Ebook Download
    View all
    Learn
    View all