我正在尝试在我的 gridview 中为即将到期的项目显示背景红色,但无法使用 asp.net

I am trying to show background red for expiring items in my gridview but not able to using asp.net

我有一个绑定到 page_load 事件的网格视图。在那里,是一个到期日期列,我希望在 30 天内和 30 天内到期的那些显示为红色。下面是我的 GridView1_RowDataBound 事件代码:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    string ddmmyyyy = DateTime.Now.ToString("dd-MM-yyyy");
    DateTime nowDate = Convert.ToDateTime(ddmmyyyy);//DateTime.ParseExact(ddmmyyyy, "dd-MM-yyyy", null);
    DateTime TableDate = Convert.ToDateTime(e.Row.Cells[6].Text);
    if (e.Row.RowIndex >= 0)
    {
        if (TableDate <= nowDate.AddDays(-30))
        {
            e.Row.Cells[6].BackColor = Color.Red;
        }
    }
}

这里是网格视图的屏幕截图。 它抛出一个异常说 the date time format is invalid。请帮我解决这个问题。

试试下面的代码。

GridView1.RowDataBound += new GridViewRowEventHandler(GridView1_RowDataBound);

void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        int value = (int)DataBinder.Eval(e.Row.DataItem, e.Row.Cells[2].Text); 
        // e.Row.Cells[2] references the cell value you want to use
        if (value < 100)
        {
            e.Row.Cells[2].BackColor = Color.FromName("#c6efce");
        }
        if ((value >= 100) && (value < 500))
        {
            e.Row.Cells[2].BackColor = Color.FromName("#ffeb9c");
        }
        if (value >= 500)
        {
            e.Row.Cells[2].BackColor = Color.FromName("#ffc7ce");
        }
    }
}

首先,您的 gridview RowDataBound 代码应符合以下条件。比尝试以下代码:

if (e.Row.RowType == DataControlRowType.DataRow)
{
    string date = "30-05-2018"; //Cell value
    DateTime getdate = Convert.ToDateTime(date, System.Globalization.CultureInfo.GetCultureInfo("en-US").DateTimeFormat);
    DateTime CurrentDate = Convert.ToDateTime(DateTime.Now, System.Globalization.CultureInfo.GetCultureInfo("en-US").DateTimeFormat);

    if ((CurrentDate - getdate).TotalDays < 30)
    {
       e.Row.Cells[6].BackColor = System.Drawing.Color.Red;
    }
}