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





Prerequisite



















Steps Involved















Step 1: Create a new asp.net website





Step2: Add a file Data.xml




<root>
	<Person>
		<Name>Person1</Name>
		<Age>17</Age>
	</Person>
	<Person>
		<Name>Person2</Name>
		<Age>18</Age>
	</Person>
	<Person>
		<Name>Person3</Name>
		<Age>19</Age>
	</Person>
</root>



Step 3: Add a grid view on a web form.






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



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();
    ds.ReadXml(Server.MapPath("Data.xml"));

    gvColor.DataSource = ds.Tables[0];
    gvColor.DataBind();
  }
  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

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250