根据DateTime.Compare更改网格视图行的颜色
本文关键字:视图 颜色 网格 DateTime Compare 根据 | 更新日期: 2023-09-27 18:29:28
如果网格视图行超过当前日期,我将尝试更改其颜色。我环顾四周,想出了一些似乎应该奏效的东西。但事实并非如此。为什么?
异常详细信息:System.NullReferenceException:对象引用未设置为对象的实例。
来源错误:
第114行:{第115行:
第116行:DateTime dt=Convert.ToDateTime(((DataRowView)e.Row.DataItem)["ExpiryDate"]);第117行:string Test=DateTime.Compare(DateTime.Now,dt).ToString();第118行:
这是我的代码
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
DateTime dt = Convert.ToDateTime(((DataRowView)e.Row.DataItem)["ExpiryDate"]);
string Test = DateTime.Compare(DateTime.Now,dt).ToString();
if (Test == "0")
{
e.Row.BackColor = System.Drawing.Color.Red;
}
else
{
e.Row.BackColor = System.Drawing.Color.White;
}
}
在使用之前,您可以检查一些对象并使用一些安全的强制转换来检查是否一切正常。
对于示例dd/MM/yyyy
或mm/DD/yyyy
,可以使用日期-时间格式进行转换,并尝试使用DateTime.TryParseExact
提取日期。我不确定你的约会时间格式,但是,你可以试试这样的东西(看看评论):
private CultureInfo enUS = new CultureInfo("en-US");
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
// check if it is a row that contains data
if (e.Row.RowType == DataControlRowType.DataRow)
{
// convert the dataItem to your datasource type with a safe cast
DataRowView row = e.Row.DataItem as DataRowView;
// check if the conversion was succeed
if (row != null)
{
// check if the date column is not null
if (row["ExpiryDate"] != null)
{
// try to convert the string into a datetime with a specific format (i am not sure about the date format you are using)
DateTime dt;
if (DateTime.TryParseExact(row["ExpiryDate"], "mm/DD/yyyy", enUS, DateTimeStyles.None, out dt))
{
// conversion looks ok, do your task
int compareResult = DateTime.Compare(DateTime.Now, dt);
e.Row.BackColor = compareResult == 0 ? System.Drawing.Color.Red : System.Drawing.Color.White;
}
}
}
}
}
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
onrowdatabound="GridView1_RowDataBound" >
<Columns>
<asp:TemplateField HeaderText="ExpiryDate">
<ItemTemplate>
<asp:Label ID="lblExpiryDate" runat="server"
Text='<%# DataBinder.Eval(Container, "DataItem.ExpiryDate") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
......
</Columns>
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string v_ExpiryDate = (string)DataBinder.Eval(e.Row.DataItem, "ExpiryDate");
string Test = DateTime.Compare(DateTime.Now,Convert.ToDateTime(v_ExpiryDate)).ToString();
if (Test == "0")
{
e.Row.BackColor = System.Drawing.Color.Red;
}
else
{
e.Row.BackColor = System.Drawing.Color.White;
}
}
}
感谢
Ashim Chatterjee