I am trying to change the color of gridview rows based on label value in a gridview. I have End Date value in the gridview, so i want to change background color if the End Date < Today's date.
<asp:GridView ID="gv_profile" runat="server" AutoGenerateColumns="false" Width="300px" OnRowDataBound="OnRowDataBound" DataKeyNames="ID" >
<Columns>
<asp:TemplateField ItemStyle-Width="10px" HeaderText="ID" >
<ItemTemplate>
<asp:Label ID="LblID" runat="server" Text='<%# Eval("ID")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="50px" HeaderText="End Date">
<ItemTemplate>
<asp:Label ID="lblEndDate" runat="server" Text='<%# Eval("End_Date", "{0: yyyy-MM-dd}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
code behind
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
}
}
that should fit your needs
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && !((e.Row.RowState == (DataControlRowState.Edit | DataControlRowState.Alternate)) || (e.Row.RowState == DataControlRowState.Edit)))
{
Label lblEndDate = (Label)e.Row.FindControl("lblEndDate");
DateTime EndDate = DateTime.Parse(lblEndDate.Text);
if (EndDate<DateTime.Today)
{
e.Row.BackColor = System.Drawing.Color.MistyRose;
}
}
}
protected void grdView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[0].Attributes.Add("onmouseover", "MouseEvents(this, event)");
e.Row.Cells[0].Attributes.Add("onmouseout", "MouseEvents(this, event)");
if ((lblhidisinsert.Value == "1") )
{
e.Row.BackColor = System.Drawing.ColorTranslator.FromHtml("#ecf8ec");
}
}
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
int id = Convert.ToInt32(e.Row.Cells[1].Text);
if (id > 0)
{
e.Row.Cells[1].ForeColor = System.Drawing.Color.Red;
}
else
{
e.Row.Cells[1].Text = Math.Abs(id).ToString();
e.Row.Cells[1].ForeColor = System.Drawing.Color.Red;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.