问题
I am not able to solve this. I want to check if the received date (DateOfRecd) is passed from current date, then it should be red.
But I cant. Please help me. My code is:
<asp:BoundField DataField="ItemTypeName" HeaderText="ItemTypeName" SortExpression="ItemTypeName" />
<asp:BoundField DataField="BrandName" HeaderText="BrandName" SortExpression="BrandName" />
<asp:BoundField DataField="ModelName" HeaderText="ModelName" SortExpression="ModelName" />
<asp:BoundField DataField="ItemSerial" HeaderText="ItemSerial" SortExpression="ItemSerial" />
<asp:BoundField DataField="DateOfRecd" HeaderText="DateOfRecd" DataFormatString="{0:dd-MMM-yy}" SortExpression="DateOfRecd" />
My C# Code is:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string v_ExpiryDate = (string)DataBinder.Eval(e.Row.DataItem, "DateOfRecd");
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;
}
}
}
回答1:
I highly doubt the value of Test
will ever be 0
. DateTime.Compare
gives 3 possible values, -1, 0 and 1. It will be negative if T1 is smaller than T2 and 1 when T1 is bigger than T2.
The value will only be 0 when the two dates are the same and that is highly unlikely since DateTime.Now
give you the time to the second. So if DateOfRecd
is not accurate to the second the moment you open the page the GridView row will never be red.
I think you only want the Date part, not the hours and seconds. So use `DateTime.Now.Date'
string Test = DateTime.Compare(DateTime.Now.Date, Convert.ToDateTime(v_ExpiryDate)).ToString();
Or just compare the dates directly.
if (DateTime.Now.Date > ExpiryDate)
{
e.Row.BackColor = System.Drawing.Color.Red;
}
来源:https://stackoverflow.com/questions/48995030/change-gridview-row-value-based-on-current-date-in-asp-net-c-sharp