如何使用 C# 根据条件更改 gridview 单元格颜色 [英] How to change gridview cell color based on condition using C#

查看:84
本文介绍了如何使用 C# 根据条件更改 gridview 单元格颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to change the color of the grdiview cell based on condition and the condition is that if Passport is about to expire with in one month or if it already expired so i want to check both condition if it is going to expire or if it already expired then i want to change the color into red. thanks

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

      }
    }

推荐答案

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

Here's a simplified piece of code that worked for me and you could easily adapt for your case:

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

这是我得到的结果:

注意我使用的是 07/15/1996 的硬编码 refDate,所以它对我本地数据库中的数据有意义.

Note I'm using a hard coded refDate of 07/15/1996, so it makes sense with data in my local database.

我做了一个间隔,只是更有趣一点:

I made it an interval, just so is a little more interesting:

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

这篇关于如何使用 C# 根据条件更改 gridview 单元格颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆