Когда у вас есть последовательности предметов, LINQ - ваш лучший друг
Предполагается, что столбец, который показывает даты, которые вы хотите закрасить, равен columnDate
DataGridViewColumn columnDate = ...
DataGridView myDataGridView = ...
var dateCells = myDataGridView.Rows.Cast<DataGridViewRow>()
.Select(row => row.Cells[columnDate.Name])
.Select(dateCell => new
{
DataGridViewCell = dateCell,
Date = DateTime.Parse(dateCell.Value.ToString()).Date,
});
Итак, Date содержит часть Date отображаемого значения в DateCell. Если вы не хотите сравнивать данные по дате, но по времени в течение 24 часов, вам следует запомнить дату и время.
Date = DateTime.Parse(dateCell.Value.ToString());
Теперь, чтобы получить клетки, которые вы хотите раскрасить:
DateTime today = DateTime.Today;
// The cells that have a date between (today - 1 day) and (today + 1 day) should be red:
var todayMinus1Day = today.AddDays(-1);
var todayPlus1Day = today.AddDays(+1);
var todayMinus1Month = today.AddMonths(-1);
var todayPlus1Month = today.AddMonths(+1)
foreach (var cell in dateCells)
{
if (todayMinus1Month <= cell.Date && cell.Date <= todayPlus1Month)
{
// either orange or red: not default:
cell.DataGridViewCell.Style = cell.DataGridViewCell.GetInheritedStyle();
cell.DataGridViewCell.Style.BackColor =
(todayMinums1Day <= cell.Date && cell.Date <= todayPlus1Day) ?
Color.Red : Color.Orange;
}
else
{ // use the inherited style = set the cell style to null
cell.DataGridViewCell.Style = null;
}
}