How To Change GridView Row's Color
Here we are binding a GridView in Asp.Net and changing row color.
Points Of Remember:
1. Fire GridView's event RowDataBound.
2. Change font color in RowDataBound event according to your logic.
3. Add namespace System.Data and System.Data.SqlClient in your C# page.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" Width="600px"
OnRowDataBound="GridView1_RowDataBound" CellPadding="4" ForeColor="#333333">
<Columns>
<asp:BoundField DataField="Name" HeaderText
="Student
Name"
/>
<asp:BoundField DataField="Branch" HeaderText="Branch" />
<asp:BoundField DataField="City" HeaderText
="City
Name"
/>
</Columns>
<HeaderStyle BackColor="#7961da" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
</asp:GridView>
</div>
</form>
</body>
using System.Data;
using System.Data.SqlClient;
public partial class GridView : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(
@"Data
Source=JITESH-PC;Initial Catalog=db_Test;Integrated Security=True"
);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridView();
}
}
// Method for binding GridView
protected void BindGridView()
{
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(
"Select
Name, Branch, City from tbl_student"
, con);
con.Open();
da.Fill(dt);
con.Close();
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.Cells[1].Text == "ECE")
{
e.Row.BackColor = System.Drawing.Color.Orange;
}
}
}