如何根据dataGridView中的DateTime值更改单元格颜色?
问题描述:
我有一个 datagridview ,它包含一个列调用' Schedule Date '。当我运行程序时,计划日期中的值应该如下所示。
如果值小于 DateTime.Today ,那么 cell 应该以RED颜色显示和其他应该出现绿色。
我很困惑。请帮我找到解决方案。
先谢谢。
I have a datagridview and it contains a column call 'Schedule Date'. When I am Running the program the values which are in 'Schedule Date' should be appear like this.
if the value is less than "DateTime.Today" , then that cell should be appear in RED colour and others should appear in GREEN color.
I am confuced. please help me to find a solution for this.
Thanks in Advance.
答
<asp:GridView runat="server" ID="gridMain" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<div style='<%# Convert.ToDateTime(DataBinder.Eval(Container.DataItem ,"Schedule_Date")) >= DateTime.Now ? "background-color:green" : "background-color:red" %>'>
<%#Eval("Schedule_Date") %>
</div>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="EmployeeName" HeaderText="Name" />
</Columns>
</asp:GridView>
foreach (DataGridViewRow row in DataGridViewRow1.Rows)
{
var now = DateTime.Now;
var cellDate = DateTime.Parse(row.Cells[14].Value.ToString());
var forTenDays = now.AddDays(+10);
if (now > cellDate)
{
row.DefaultCellStyle.BackColor = Color.Red;
}
else if ((now < cellDate) && (cellDate < forTenDays))
{
row.DefaultCellStyle.BackColor = Color.Yellow;
}
else
{
row.DefaultCellStyle.BackColor = Color.LightGreen;
}
}