Click here to Skip to main content
16,004,678 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hello coders,

I've been struggling with something regarding datagridview row painting for better usage and understanding.

What I want to do:

Simply change the color of the column if the value(it's a date value) is less then 5 days to reach the today's date (DateTime.Now()).

What I have tried:

C#
foreach (DataGridViewRow row in dgw.Rows)
                   {
                    var now = DateTime.Parse(DateTime.Now.ToShortDateString());
                    var cellendDate = DateTime.Parse(row.Cells[5].Value.ToString());
                    var forTenDays = now.AddDays(+5);
                    var cellstartDate = DateTime.Parse(row.Cells[4].Value.ToString());
                    if (cellstartDate > cellendDate)
                    {
                        row.DefaultCellStyle.BackColor = Color.Gray;
                    }                 
                    else if ((now < cellendDate) && (cellendDate < forTenDays))
                    {
                        row.Cells[5].Style.BackColor = Color.Yellow; 
                    }else if (now == cellendDate)
                    {
                        row.Cells[5].Style.BackColor = Color.Red;
                    }else
                    {
                        row.Cells[5].Style.BackColor = Color.YellowGreen;
                    }
                }
Posted
Updated 27-Apr-17 4:09am
v3
Comments
[no name] 27-Apr-17 9:57am    
"I've been struggling", is not a description of any kind of a problem. If you are wanting to do something for 5 day difference then why are you adding 10 days?
Scribling Doodle 27-Apr-17 10:08am    
5, 10, 30 it's the same thing... I forgot to edit that since I was testing some stuff. I'm sorry.
PIEBALDconsult 27-Apr-17 10:03am    
DateTime.Parse(DateTime.Now.ToShortDateString()) -- PLEASE don't do that! Just use DateTime.Now
If you subtract cellstartDate or cellendDate from DateTime.Now you get a TimeSpan.
You can then simply test the timeSpan's TotalDays Property.

1 solution

To start with, don't use this:
var now = DateTime.Parse(DateTime.Now.ToShortDateString());

Instead use this:
DateTime now = DateTime.Now.Date;

And don't change cell values to a string and then parse them back to DateTimes either: if they are DateTime values in the cell, then cast them:
DateTime cellendDate = (DateTime)row.Cells[5].Value;

If you want five days, then add 5 not 10...
 
Share this answer
 
Comments
Scribling Doodle 27-Apr-17 10:11am    
I'll try, and already edited the question, since I was testing out some values, I forgot about that 10... But already changed it.
Maciej Los 27-Apr-17 14:35pm    
5ed!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900