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

标签 c# asp.net .net gridview

我想根据条件更改 grdiview 单元格的颜色,条件是如果 Passport 将在一个月内过期或已经过期,所以我想检查这两个条件是否即将过期或如果它已经过期,那么我想将颜色更改为红色。谢谢

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

      }
    }

最佳答案

这是一段对我有用的简化代码,您可以轻松地适应您的情况:

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

请注意,我使用的是 07/15/1996 的硬编码 refDate,因此它对我本地数据库中的数据有意义。

编辑:我把它设为一个间隔,这样更有趣一点:

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

关于c# - 如何使用 C# 根据条件更改 gridview 单元格颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31528633/

相关文章:

c# - GridView 按钮通过单击传递数据

mysql - 从MySQL读取数据到VB

c# - 将不同版本的 c# 和 .NET Framework 与 dll 一起使用

c# - 忽略多个标准不起作用的问题

c# - 如何在 Windows Mobile 6.5 上终止进程

c# - 使用自定义身份数据库代替 ASP.NET core Identity

c# - 您如何测试执行文件 IO 的代码?

asp.net - 系统NullReferenceException : Object reference not set to an instance of an object:

c# - 从 .NET 执行 Cygwin 进程?

c# - IEnumerable<T> 到 CSV 文件