Here i have explained how to change Dynamically GridView Row Background Color in Asp.Net C#.

Step 1) Add HTML:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title> Dynamically change GridView Row Background Color in Asp.Net C#.</title>
<style type="text/css">
body
{
font-family:Calibri;
}
.btechcss
{
background:#df5015;
font-weight:bold;
color:White;
}
.bacss
{
background:Green;
font-weight:bold;
color:White;
}

table, th, td {
border: 1px solid black;
padding: 4px 10px 4px 10px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<h1>Dynamically change GridView Row Background Color in Asp.Net C#.</h1>
<div>
<asp:GridView ID="gvDetails" runat="server" OnRowDataBound="gvDetails_RowDataBound">
</asp:GridView>
</div>
</form>
</body>
</html>

Step 2) Import Namespaces

using System;
using System.Data;
using System.Web.UI.WebControls;

Step 3) C#

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, "Imran Khan", "B.Tech");
dt.Rows.Add(2, "Fatima Ali", "CA");
dt.Rows.Add(3, "Ram Shankar", "BA");
dt.Rows.Add(4, "Narendra Tiwari", "B.Tech");
dt.Rows.Add(6, "Mani Anuragam", "MD");
dt.Rows.Add(7, "Waseem Mirza", "B.Tech");
dt.Rows.Add(8, "Bilal Ahmed", "BA");
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("BA"))
{
row.CssClass = "bacss";
}
}
}
}

Screenshot

Add Comments