簡體   English   中英

基於asp.net C#中的當前日期更改Gridview行值

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

我無法解決此問題。 我想檢查接收日期(DateOfRecd)是否從當前日期過去,那么它應該是紅色的。

但是我不能。 請幫我。 我的代碼是:

<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" />

我的C#代碼是:

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;
        }
    }
}

我非常懷疑Test的值將永遠為0 DateTime.Compare給出3個可能的值,-1、0和1。如果T1小於T2,則為負;當T1大於T2時,為1。 僅當兩個日期相同時該值才為0,並且由於DateTime.Now可能性很小,現在可以給您第二個時間。 因此,如果DateOfRecd到打開頁面的那一刻不准確,則GridView行將永遠不會為紅色。

我認為您只需要日期部分,而不是小時和秒。 所以使用`DateTime.Now.Date'

string Test = DateTime.Compare(DateTime.Now.Date, Convert.ToDateTime(v_ExpiryDate)).ToString();

或者直接比較日期。

if (DateTime.Now.Date > ExpiryDate)
{
    e.Row.BackColor = System.Drawing.Color.Red;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM