2015-07-21 107 views
6

我想根据条件改变grdiview单元格的颜色,条件是如果Passport即将在一个月内过期,或者它已经过期,所以我想检查两种情况是否会过期或者是否已经过期,那么我想将颜色更改为红色。感谢如何根据条件改变gridview单元格颜色使用C#

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

     } 
    } 
+0

检查这个 http://stackoverflow.com/questions/4427848/change-cell-color-on-different-values-gridview –

+0

我有类似的逻辑,但仍然不适用于我 – moe

+0

请参阅这篇文章http://codepedia.info/2015/04/gridview-row -color-change-based-on-data-asp-net -c /你可以使用'e.Row.Cell [3] .CssClass = setColorClass;' –

回答

7

下面是一个简单的一块为我工作的代码,你可以轻松地适应您的情况:

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

相关问题