Reputation: 540
I have rows of information stored in a grid view, each containing a date. This date is historic and I would like to colour code the date if it is over a year old and also if it is between 10 months and a year old.
Here is the code that I have at the moment:
foreach(GridViewRow row in gridview.Rows){
if (e.Row.RowType == DataControlRowType.DataRow)
{
DateTime datepaid = Convert.ToDateTime(DataBinder.Eval(e.Row.DataItem, "date_stored"));
DateTime date_now = DateTime.Now;
TextBox1.Text = (date_sub_paid - DateTime.Now).ToString();
if ((datepaid - DateTime.Now).Days >= -365)
{
e.Row.Cells[4].ForeColor = System.Drawing.Color.Red;
e.Row.Cells[4].Font.Bold = true;
}
else if ((datepaid - date_now).Days >= -305 && (datepaid - date_now).Days < -365)
{
e.Row.ForeColor = System.Drawing.Color.Yellow;
}
else
{
e.Row.ForeColor = System.Drawing.Color.Black;
}
}
}
There is a flaw in my logic as this the output is not as expected. Would anyone be able to help with this? Thanks in advance.
EDIT:::
I have edited the code and it now looks like it works correctly:
foreach(GridViewRow row in subtracker_gridview.Rows){
if (e.Row.RowType == DataControlRowType.DataRow)
{
DateTime datepaid= Convert.ToDateTime(DataBinder.Eval(e.Row.DataItem, "DATE"));
DateTime date_now = DateTime.Now;
TextBox1.Text = (date_now - datepaid).Days.ToString();
if ((date_now - datepaid).Days >= 365)
{
e.Row.Cells[4].ForeColor = System.Drawing.Color.Red;
e.Row.Cells[4].Font.Bold = true;
}
else if ((date_now - datepaid).Days >= 335 && (date_now - datepaid).Days < 365)
{
e.Row.Cells[4].ForeColor = System.Drawing.Color.Gold;
e.Row.Cells[4].Font.Bold = true;
}
else
{
e.Row.Cells[4].ForeColor = System.Drawing.Color.Green;
e.Row.Cells[4].Font.Bold = true;
}
}
However, the first row seems to be ignored and does not get coloured? Any ideas why this is happening? Thanks for your help.
EDIT #2: I removed the foreach loop. This was not needed and caused the first date to be ignored.
Upvotes: 2
Views: 1852
Reputation: 3034
I don't think anything can satisfy the conditional:
if ((datepaid - date_now).Days >= -305 && (datepaid - date_now).Days < -365)
I can't think of any values that are greater than or equal to -305 that are also less than -365.
You would also probably be better off calculating whatever your "Elapsed Time" is once and then saving it in a local variable, and then using that value a bunch of times. Otherwise, at some point in the future, someone is going to change (datepaid - date_now)
to something else, but then miss it in another place.
Upvotes: 1
Reputation: 4795
Second condition is never true. There is no number that is greater than -305 and less than -365 Also if the first half of the second condition is true it won't be reached because the first condition would be true too. Save yourself the confusion and subtract now from the parsed date and deal with positive numbers.
Upvotes: 2