I have a column called Review Date
from MySQL. Formatted as dd/mm/yyyy
.
I simply show it on the dataGridView.
I am trying to create a statement to compare today's date to the dataGrid values.
Here is what I have tried:
private void data_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
DateTime today = DateTime.Today;
string todayDate = today.ToString("d/M/yyyy");
foreach (DataGridViewRow Myrow in data.Rows)
{
// Cell 6 is the review_date
if (Myrow.Cells[6].Value.ToString() < todayDate)
{
Myrow.DefaultCellStyle.BackColor = Color.Red;
}
else
{
Myrow.DefaultCellStyle.BackColor = Color.Green;
}
}
}
But I get an error:
Operator '<' cannot be applied to operands of type 'string' and 'string'
You should use Date
objects.
DateTime today = DateTime.Now;
foreach (DataGridViewRow Myrow in data.Rows)
{
DateTime dt = DateTime.Parse(Myrow.Cells[6].Value.ToString());
if (dt > today)
{
Myrow.DefaultCellStyle.BackColor = Color.Red;
}
else
{
Myrow.DefaultCellStyle.BackColor = Color.Green;
}
}
Also, quick tip.
If you'd like to add days or months to your date. Try this...
//Add days
if (dt > today.AddDays(10))
//Add months
if (dt > today.AddMonths(12))
You can't do a less than operator on strings like that. You need to do the comparison the date objects. Something like this perhaps.
private void data_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
DateTime today = DateTime.Today.Date; //Used .Date to cut off time too
foreach (DataGridViewRow Myrow in data.Rows)
{
var GridDate = DateTime.Today.Date;
DateTime.TryParse(Myrow.Cells[6], out GridDate); //parse string date
//Cell 6 is the review_date
if (GridDate < todayDate)
{
Myrow.DefaultCellStyle.BackColor = Color.Red;
}
else
{
Myrow.DefaultCellStyle.BackColor = Color.Green;
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.