2013-03-22 92 views
0

我的代码工作的行改变颜色,但我需要if语句做出正确的。在单元格[0]中,我有日期值“2013.03.20”。此日期表示产品过期日期。datagridview的更改行的颜色,当日期过期或更少

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

实施例:

  • 今天是2013年3月10日
  • 产品过期日期是2013年3月20日。
  • 最后7天的产品到期将给黄色。 (即,从13日至20日)
  • 当产品到期,我想它显示为红色。
+1

DataField的名称是什么..你可以使用Index或字段名来做到这一点..我个人会通过fieldname这样做,如果数据结构发生变化,你不必担心更新整个代码中的FiledName索引值.. – MethodMan 2013-03-22 14:21:28

回答

3

正如西蒙说,你还应该为日期时间处理不正确的日期格式。

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

使用你的变种:) Thx为你提供所有帮助。你的代码将存储在我的大脑:) – user2182959 2013-03-22 14:46:01

4

像这样的东西(离开我的头顶,没有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; 
       } 
+1

准确地说,我会发布回复的样式! + 1 – 2013-03-22 14:20:06

+0

我写我的条件。如果今天的日期已经离开了7天然后黄色,今天是大的,然后过期日期然后是红色。 – user2182959 2013-03-22 14:21:58

0

您可以使用的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; 
     } 
    } 

} 
+0

虽然这不是asp.net ... – 2015-07-23 12:05:56

0

试试这个例子。

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 
}