我试图更改一个网格视图上的过期日期列。当过期日期早于当前日期或距离当前日期在15天内时,我想将其颜色改为红色;当距离当前日期在15到30天时,我想将其颜色改为黄色。当我尝试实现rowdatabound并设置datetime变量时,我发现丢失了gridview中的某些行,并且颜色没有显示。
<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>
代码后台,
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;
}
}
}