我有一个来自MySQL的名为review date
的专栏。 格式为DD/MM/YYYY
。
我只是在DataGridView上显示它。
在此处输入图像说明
我正在尝试创建一条语句,将今天的日期与dataGrid值进行比较。
下面是我尝试的方法:
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;
}
}
}
但我得到了一个错误:
运算符'<' 不能应用于“string”和“string”类型的操作数
您应该使用date
对象。
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;
}
}
还有,快速小费。
如果你想增加几天或几个月的约会时间。 试试这个。。。
//Add days
if (dt > today.AddDays(10))
//Add months
if (dt > today.AddMonths(12))
你不能对这样的字符串执行小于运算符。 您需要对日期对象进行比较。 也许是这样的。
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;
}
}
}