How to change grid cell color based on condition using C #

I want to change the color of the grdiview cell based on the condition, and the condition is if the passport expires after one month or if it has already expired, so I want to check both conditions if it expires or if it has already expired, then I want change color to 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; } } } 
+6
source share
1 answer

Here's the simplified part of the code that worked for me, and you could easily adapt to 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; } } } 

As a result, I get:

enter image description here

Note. I am using hardcoded refDate from 07/15/1996, so it makes sense with the data in my local database.

EDIT: I did this at intervals, just 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; } } } 

enter image description here

+7
source

All Articles