C# Winforms: How to Change the DataGridView Row Color based on Expiry Date

Omer Butt 96 Reputation points
2021-10-08T16:23:03.763+00:00

Its not a ASP.net Question hence no RowDataBound Event Works here in this question please answer according to Winforms DataGridView which Event handler to be used to solve this question.

I want to change the row color of DataGridView based on Expiry Date.

If the Expiry date is >= to the value of Expiry Date Column the Row Color change to Red

and If one month left to be Expired then the row color change to Yellow.

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,833 questions
0 comments No comments
{count} votes

Accepted answer
  1. Omer Butt 96 Reputation points
    2021-10-09T12:57:05.713+00:00

    @Viorel After trying and researched I finally achieved the desired result

    by using RowPrePaint Event and below is the right way:

    private void dgv_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)  
            {  
                var ExpiryDate = Convert.ToDateTime(dgv.Rows[e.RowIndex].Cells[7].Value);   
                var TodayDate = DateTime.Today;  
                var Expired = ExpiryDate >= TodayDate;  
                var ExpiredToBe = ExpiryDate >= TodayDate.AddDays(-30);  
                if (Expired)  
                {  
                    dgv.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.LightCoral;  
                }  
                else if (ExpiredToBe)  
                {  
                    dgv.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Gold;  
                }  
            }  
    
    0 comments No comments

1 additional answer

Sort by: Most helpful