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
- Knowledge of ASP.NET.
- Knowledge of C#.
- How to create xml files?
- How to create projects using visual studio?
Steps Involved
- Create a new asp.net website
- Add a file Data.xml
- Add a grid view on a web form
- Define the criteria for coloring the rows
- 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
Click to Enlarge