Articles → ASP .NET GRIDVIEW → Set the row background in gridview in

Set the row background in gridview in

Objective of this Tutorial


Steps Involved

Step 1: Create a new 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:Label>
            <asp:TemplateField HeaderText="Age">
                    <asp:Label ID="lblAge" runat="server" Text='<%#Eval("Age") %>'></asp:Label>

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

Click to Enlarge

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


Your Email Id  
Query/FeedbackCharacters remaining 250