Tuesday, April 07, 2015

Change Asp.Net GridView Row Background Color Based on Condition in C# and VB.Net


Introduction:
Here I will explain how dynamically change asp.net gridview row background color based on condition in asp.net using css classes in c#, vb.net with example.
I will use _RowDataBound event to check the case and change the css for each row. you will see we will create a event for RowDataBound, its easy and great work.

.aspx page HTML

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title> Dynamically change GridView Row Background Color based on condition in ASP.Net using C# and VB.Net</title>
<style type="text/css">
body
{
font-family:Calibri;
}
.btechcss
{
background:#df5015;
font-weight:bold;
color:White;
}
.mscss
{
background:Green;
font-weight:bold;
color:White;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvDetails" runat="server" OnRowDataBound="gvDetails_RowDataBound" BorderStyle="Dashed" BorderWidth="1px" Caption="Employee List" CaptionAlign="Top">
</asp:GridView>
</div>
</form>
</body>
</html>

 Here
 open code behind file and add following code.

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
BindGridview();
}
private void BindGridview()
{
DataTable dt = new DataTable();
dt.Columns.Add("UserId", typeof(Int32));
dt.Columns.Add("UserName", typeof(string));
dt.Columns.Add("Education", typeof(string));
dt.Rows.Add(1, "Asma Qureshi", "B.Tech");
dt.Rows.Add(2, "Daniel Fakher", "Msc");
dt.Rows.Add(3, "Faheem Shah", "Ms");
dt.Rows.Add(4, "Praveen Fareeq", "B.Tech");
dt.Rows.Add(6, "Davied Fernandes", "MD");
dt.Rows.Add(7, "Thomus Brows", "B.Tech");
dt.Rows.Add(8, "Waseem Shaikh", "CA");
gvDetails.DataSource = dt;
gvDetails.DataBind();
}
protected void gvDetails_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
foreach (TableCell row in e.Row.Cells)
{
if (e.Row.Cells[2].Text == "B.Tech")
{
row.CssClass = "btechcss";
}
if (e.Row.Cells[2].Text.Contains("Ms"))
{
row.CssClass = "mscss";
}
}
}
}


Download Code from below link



No comments:

Post a Comment