根据列日期更改DataGridView中的行颜色

时间:2016-11-22 18:23:05

标签: c# datagridview rows

我有一个DataGridView有几列,一个是"校准到期日"。如果校准截止日期已经过去,我正在寻找一种方法将行的颜色更改为红色,如果校准截止日期前不到一个月,我会寻找蓝色。

我尝试过以下代码,但没有做任何事情:

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;
    }
}

3 个答案:

答案 0 :(得分:0)

CellFormatting事件中执行此操作:

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;
    }
}

答案 1 :(得分:0)

您可以使用DataGridViewRow.Cells属性:

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;
    }
}

答案 2 :(得分:0)

我把代码放在错误的地方。我已将以下代码放入另一种形式的源代码(用于在DataGridView中输入详细信息的表单),现在它正在运行:

 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;
            }
        }