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










  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 asp.net 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




<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




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


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

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250