根据列日期更改DataGridView中的行颜色 [英] Change row color in DataGridView based on column date
问题描述
我有一个 DataGridView
,其中有几列,其中一列是校准到期日。我正在寻找一种方法,如果校准到期日期已过,则将行的颜色更改为红色,如果校准到期日期还不到一个月,则将其更改为蓝色。
I have got a DataGridView
with several columns, one being the "Calibration Due Date". I'm looking for a way to change the color of a row to RED if the calibration due date has passed, and to BLUE if there is less than one month until the calibration due date.
我尝试了以下代码,但没有执行任何操作:
I have tried the following code which didn't do anything:
private void Form1_Load(object sender, EventArgs e)
{
foreach (DataGridView row in instrumentsDataGridView.Rows)
{
var now = DateTime.Now;
var expirationDate = DateTime.Parse(instrumentsDataGridView.Columns["CalibrationDue"].ToString());
var Month = expirationDate.AddDays(-30);
if (now > Month && now < expirationDate)
row.DefaultCellStyle.BackColor = Color.Blue;
else if (now > expirationDate)
row.DefaultCellStyle.BackColor = Color.Red;
}
}
推荐答案
I将代码放在错误的位置。我已经将以下代码放入另一个表单的源代码(用于在 DataGridView
中输入详细信息的表单)中,并且现在可以正常工作:
I was putting the code in the wrong place. I've put the following code into another form's source code (form for entering details into the DataGridView
) and it is now working:
DateTime now = DateTime.Now, thirtyDaysAgo = now.AddDays(-30), expirationDate;
foreach (DataGridViewRow row in form.instrumentsDataGridView.Rows)
{
string cellText = row.Cells["CalibrationDue"].Value + "";
if (DateTime.TryParse(cellText, out expirationDate))
{
if (expirationDate < now)
row.DefaultCellStyle.BackColor = Color.Red;
else if (expirationDate > thirtyDaysAgo)
row.DefaultCellStyle.BackColor = Color.PaleTurquoise;
}
}
这篇关于根据列日期更改DataGridView中的行颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!