I am trying to change the expiration date column in a gridview. I want to change the color when I'm outside the current date, or within 15 days from the current date the color changes to red, and if from 15 to 30 days from the current data date, set the color to yellow. When I try to implement rowdatabound while trying to set the datetime variable, I miss the rows from the gridview and the colors are not displayed.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AllowSorting="True" OnDataBound="GridView1_DataBound" OnRowDataBound="GridView1_RowDataBound1">
<Columns>
<asp:BoundField DataField="MLSId" HeaderText="MLSId" SortExpression="MLSId" />
<asp:BoundField DataField="Agent_FName" HeaderText="First Name" SortExpression="Agent_FName" />
<asp:BoundField DataField="Agent_LName" HeaderText="Last Name" SortExpression="Agent_LName" />
<asp:BoundField DataField="License_Num" HeaderText="License #" SortExpression="License_Num" />
<asp:TemplateField HeaderText="License Exp" SortExpression="License_Exp">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("License_Exp") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("License_Exp", "{0:MM/dd/yyyy}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The code,
protected void GridView1_RowDataBound1(object sender, GridViewRowEventArgs e)
{
for (int i = 0; i <= GridView1.Rows.Count-1; i++)
{
DateTime lblDate = Convert.ToDateTime(GridView1.Rows[i].FindControl("Label1"));
if (lblDate <= DateTime.Now.AddDays(15))
{
GridView1.Rows[i].Cells[4].BackColor = Color.Red;
}
else if (lblDate >= DateTime.Now.AddDays(16) && lblDate <= DateTime.Now.AddDays(30))
{
GridView1.Rows[i].Cells[4].BackColor = Color.Yellow;
}
else
{
GridView1.Rows[i].Cells[4].BackColor = Color.Blue;
}
}
}
source
share