问题
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;
}
}
回答1:
Do it in the CellFormatting
event:
private void DataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.ColumnIndex == instrumentsDataGridView.Columns["CalibrationDue"].Index)
{
if (e.Value == null)
return;
var now = DateTime.Now;
var expirationDate = (DateTime)e.Value;
var month = expirationDate.AddDays(-30);
var row = instrumentsDataGridView.Rows[e.RowIndex];
if (now > month && now < expirationDate)
row.DefaultCellStyle.BackColor = Color.Blue;
else if (now > expirationDate)
row.DefaultCellStyle.BackColor = Color.Red;
}
}
回答2:
You can use the DataGridViewRow.Cells Property:
DateTime now = DateTime.Now, thirtyDaysAgo = now.AddDays(-30), expirationDate;
foreach (DataGridViewRow row in 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.Blue;
}
}
回答3:
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;
}
}
来源:https://stackoverflow.com/questions/40749012/change-row-color-in-datagridview-based-on-column-date