Change Gridview row value based on current date in asp.net C#

人走茶凉 提交于 2019-12-11 17:26:00

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!