【问题标题】:Change DataGridView row color based on current date根据当前日期更改 DataGridView 行颜色
【发布时间】:2018-03-12 21:09:35
【问题描述】:

我有一个带有Date 列的DataGridView 控件。我想根据该列中与当天相比的值设置每一行的颜色:

如果我的网格中的日期至少还有 15 天,请保留默认颜色。如果我的网格中的日期只有 5 天,请使用橙色。如果日期只有 1 天,请使用红色。

我该怎么做?

【问题讨论】:

  • 您可以为 datagridview 使用CellFormatting 事件并在其中检查它是否是所需的列,根据DateTime.Now 检查其值并更改此单元格Style.BackColor

标签: c# winforms datetime datagridview


【解决方案1】:

创建两个函数,一个用于遍历所有行,另一个用于为行中的所有单元格着色。

private void ColorDates()
{
    if (dataGridView1.Rows.Count <= 0)
    {
        MessageBox.Show("Datagridview is empty!");
        return;
    }

    foreach(DataGridViewRow row in dataGridView1.Rows)
    {
        DateTime value = Convert.ToDateTime(row.Cells["DateColumn"].Value);
        DateTime citeria = new DateTime(2018, 28, 02);

        int result = DateTime.Compare(value, citeria);

        if (result < 0) //value is earlier than citeria
            ColorRow(row, Color.Red);
        else if (result == 0) //Value is equal to citeria
            ColorRow(row, Color.Green);
        else if (result > 0) //value is later than citeria
            ColorRow(row, Color.Blue);
    }
}

private void ColorRow(DataGridViewRow row, Color color)
{
    foreach(DataGridViewCell cell in row.Cells)
    {
        cell.Style.BackColor = color;
    }
}

使用ColorDates()将数据绑定到datagridview后调用它

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-06
    • 1970-01-01
    • 1970-01-01
    • 2018-05-12
    • 1970-01-01
    • 2013-03-12
    • 2018-03-16
    • 1970-01-01
    相关资源
    最近更新 更多