当日期过期或更短时,Datagridview更改行颜色

本文关键字:Datagridview 颜色 日期 过期 | 更新日期: 2023-09-27 18:05:23

我的代码用于更改行中的颜色,但我需要做出正确的if语句。在单元格[0]中,我有日期值"2013.03.20"。此日期为产品过期日期。

foreach (DataGridViewRow row in dataGridView1.Rows)
{
  if (row.Cells[0](dont know how write))
  {
   row.DefaultCellStyle.BackColor = Color.Red;
  }
}

的例子:

  • 今天是2013.03.10
  • 产品过期日期为2013.03.20。
  • 产品有效期最后7天呈黄色。(即13日至20日)
  • 当产品过期时,我想显示为红色。

当日期过期或更短时,Datagridview更改行颜色

大概是这样的(我没有使用Visual Studio,所以请原谅任何语法错误)。您可能需要在DateTime转换方面更健壮一些,以处理空值、无效日期等。您可以调整条件以匹配您的确切需求:

 foreach (DataGridViewRow row in dataGridView1.Rows)
                switch (Convert.ToDatetime(row.Cells[0].ToString()))
                {
                   case > DateTime.Today:
                      row.DefaultCellStyle.BackColor = SomeColor;  
                      break;
                   case == DateTime.Today:
                      row.DefaultCellStyle.BackColor = SomeColor;  
                      break;
                    case else:
                      row.DefaultCellStyle.BackColor = SomeColor;  
                      break;
                }

正如Simon所说,你还应该处理DateTime的错误日期格式。

foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            var now = DateTime.Now;
            var expirationDate =  DateTime.Parse(row.Cells[0].Value.ToString());
            var sevenDayBefore = expirationDate.AddDays(-7);
            if (now > sevenDayBefore && now < expirationDate)
            {
                row.DefaultCellStyle.BackColor = Color.Yellow;
            }
            else if (now > expirationDate)
            {
                row.DefaultCellStyle.BackColor = Color.Red;    
            }
        }

试试这个例子。

DateTime currentToday = (DateTime)this.dataGridView1.Rows[e.RowIndex].Cells["Date"].Value;
if (currentToday <= DateTime.Now.Date)
{
      e.CellStyle.ForeColor = Color.Red; //Font Color
      e.CellStyle.SelectionForeColor = Color.Red; //Selection Font color
}

您可以使用RowDataBound事件处理程序而不是使用foreach。我认为使用RowDataBound事件处理程序是为那些事情。

public void dataGridView1_RowDataBound(Object sender, GridViewRowEventArgs e)  
{
    if(e.Row.RowType == DataControlRowType.DataRow)
    {
        Product currentProduct = e.Item.DataItem as Product;
        TimeSpan diffDate = DateTime.Now - currentProduct.ExpireDate;
        if (dateDiff < TimeSpan.FromDays(0))
        {
            row.DefaultCellStyle.BackColor = Color.Yellow;
        }
        else if (dateDiff < TimeSpan.FromDays(7))
        {
            row.DefaultCellStyle.BackColor = Color.Red;
        }
    }  
}