如何使用C#根据条件更改GridView单元格颜色

8
我想根据条件更改grdiview单元格的颜色,条件是如果护照一个月内即将过期或已经过期,我想检查两个条件,如果它即将过期或已经过期,那么我想将其颜色更改为红色。谢谢
protected void OnRowDataBound_gvPass(object sender, GridViewRowEventArgs e)
    {
      DateTime todaysDate = DateTime.Now.Date;
      if (e.Row.RowType == DataControlRowType.DataRow)
      {


        Label lblPassportExpDate = (Label)e.Row.FindControl("PassportExpDate");
        DateTime PassportExpDateDate = DateTime.Parse(lblPassportExpDate.Text);
        if (PassportExpDateDate < DateTime.Today || PassportExpDateDate < todaysDate.AddDays(30))
        {
          //e.Row.BackColor = System.Drawing.Color.Red;
          gvDriverStatus.Columns[3].ItemStyle.ForeColor = System.Drawing.Color.Red;
        }

      }
    }

请检查以下链接:https://dev59.com/wlLTa4cB1Zd3GeqPcJ0H - Mo A
我有类似的逻辑,但是对我来说仍然不起作用。 - moe
1个回答

9
这是一段对我有效且你能轻松适应的简化代码:

protected void Page_Load(object sender, EventArgs e)
{
    refDate = new DateTime(1996, 7, 15);
}

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowIndex >= 0)
    {
        if (DateTime.Parse(e.Row.Cells[3].Text) < refDate)
        {
            e.Row.Cells[3].BackColor = Color.Red;
        }
    }
}

这是我得到的结果: enter image description here 请注意,我使用了硬编码的refDate,为07/15/1996,这样与我的本地数据库中的数据相符。
编辑:我将其设置为时间间隔,这样更有趣一些。
protected void Page_Load(object sender, EventArgs e)
{
    minDate = new DateTime(1996, 7, 7);
    maxDate = new DateTime(1996, 7, 15);
}

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowIndex >= 0)
    {
        var curDate = DateTime.Parse(e.Row.Cells[3].Text);

        if (minDate < curDate && curDate < maxDate)
        {
            e.Row.Cells[3].BackColor = Color.Red;
            e.Row.Cells[3].ForeColor = Color.White;
        }
    }
}

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接