Articles → ASP .NET GRIDVIEW → Set The Row Background In Gridview In Asp.Net

Set The Row Background In Gridview In Asp.Net

Objective Of This Tutorial


  1. Knowledge of ASP.NET.
  2. Knowledge of C#.
  3. How to create xml files?
  4. How to create projects using visual studio?

Steps Involved

  1. Create a new website
  2. Add a file Data.xml
  3. Add a grid view on a web form
  4. Define the criteria for coloring the rows
  5. Execute the code

Step 1: Create A New Asp.Net Website

Step2: Add A File Data.Xml


Step 3: Add A Grid View On A Web Form.

<asp:GridView ID="gvColor" runat="server" onrowdatabound="gvColor_RowDataBound" AutoGenerateColumns="false">
		<asp:TemplateField HeaderText="Name">
				<asp:Label ID="lblName" runat="server" Text='<%#Eval("Name") %>'>
		<asp:TemplateField HeaderText="Age">
				<asp:Label ID="lblAge" runat="server" Text='<%#Eval("Age") %>'>

Step 4: Define The Criteria For Coloring The Rows

using System;
using System.Web.UI.WebControls;
using System.Data;

public partial class _Default: System.Web.UI.Page {
  protected void Page_Load(object sender, EventArgs e) {
    DataSet ds = new DataSet();

    gvColor.DataSource = ds.Tables[0];
  protected void gvColor_RowDataBound(object sender, GridViewRowEventArgs e) {
    if (e.Row.RowType == DataControlRowType.DataRow) {
      Label lblAge = (Label) e.Row.FindControl("lblAge");

      if (Convert.ToInt16(lblAge.Text) < 18)
        e.Row.Attributes.Add("style", "background-color:red");


Step 5: Execute The Code

Picture showing the output of setting the row background in gridview in
Click to Enlarge

Posted By  -  Karan Gupta
Posted On  -  Tuesday, March 25, 2014


Your Email Id  
Query/FeedbackCharacters remaining 250