Change Gridview ROW color according to Data Value.
Change Gridview ROW color according to Data Value.
Step 1: Design web form .aspx page
<div>
<asp:GridView ID="gr" runat="server" AutoGenerateColumns="false" AlternatingRowStyle-BackColor="WhiteSmoke" Width="40%" OnRowDataBound="gr_RowDataBound">
<HeaderStyle BackColor="#3366ff" Font-Bold="true" ForeColor="White" />
<Columns>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lbl_Name" runat="server" Text='<%#Eval("Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="Phone" HeaderText="Phone" />
<asp:TemplateField HeaderText="Percentage">
<ItemTemplate>
<asp:Label ID="lbl_Perc" runat="server" Text='<%#Eval("percentage") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
Step 2: Logic on .CS Page
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Bind
Gridview
bind_gr();
}
}
public void bind_gr()
{
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("City");
dt.Columns.Add("Phone");
dt.Columns.Add("percentage");
dt.Rows.Add("Kandy", "Delhi", "8802***2564", "54");
dt.Rows.Add("Sam", "Hr", "545502*2544", "32");
dt.Rows.Add("Izhar", "Up", "95802*2452", "90");
dt.Rows.Add("Vineet", "Delhi", "88022564***", "31");
gr.DataSource = dt;
gr.DataBind();
}
protected void gr_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lblper = e.Row.FindControl("lbl_Perc") as Label;
if (Convert.ToInt32(lblper.Text) < 33)
{
e.Row.BackColor =
System.Drawing.Color.Honeydew;
}
else if(Convert.ToInt32(lblper.Text) <60 )
{
e.Row.BackColor =
System.Drawing.Color.Yellow;
}
else if (Convert.ToInt32(lblper.Text) < 99)
{
e.Row.BackColor =
System.Drawing.Color.Pink;
}
}
}
Comments
Post a Comment