You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据日期列与当前日期的差值设置DataGridView行颜色?

实现DataGridView根据日期距离动态设置行颜色

嘿,这个需求在WinForms开发里挺常见的,我来给你一步步讲怎么实现:

核心思路

我们需要利用DataGridView的CellFormatting事件(这个事件会在每个单元格准备渲染时触发,适合动态调整样式),在事件处理中完成这几件事:

  1. 获取当前日期(用DateTime.Today去掉时间部分,避免时间差干扰计算)
  2. 解析每行的Date列值为DateTime类型
  3. 计算该日期与当前日期的剩余天数
  4. 根据剩余天数范围设置对应行的背景色

C# 代码实现

第一步:绑定事件

在窗体的构造函数或者Load事件中,给DataGridView绑定CellFormatting事件:

public YourForm()
{
    InitializeComponent();
    // 绑定CellFormatting事件
    dataGridView1.CellFormatting += DataGridView1_CellFormatting;
}

第二步:编写事件处理逻辑

private void DataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    // 只处理名为"Date"的列,也可以用列索引(比如e.ColumnIndex == 0)
    if (dataGridView1.Columns[e.ColumnIndex].Name == "Date" && e.RowIndex != dataGridView1.NewRowIndex)
    {
        // 尝试解析单元格值为DateTime,避免格式错误导致崩溃
        if (DateTime.TryParse(e.Value?.ToString(), out DateTime rowDate))
        {
            DateTime today = DateTime.Today;
            // 计算剩余天数:目标日期减去当前日期的总天数,取整数部分
            int daysRemaining = (int)(rowDate.Date - today.Date).TotalDays;

            DataGridViewRow currentRow = dataGridView1.Rows[e.RowIndex];
            
            // 根据剩余天数设置背景色
            if (daysRemaining <= 1)
            {
                currentRow.DefaultCellStyle.BackColor = Color.Red;
            }
            else if (daysRemaining <= 5)
            {
                currentRow.DefaultCellStyle.BackColor = Color.Orange;
            }
            else
            {
                // 恢复默认背景色,防止排序/刷新后样式残留
                currentRow.DefaultCellStyle.BackColor = dataGridView1.DefaultCellStyle.BackColor;
            }
        }
    }
}

VB.NET 代码实现

如果用VB.NET开发,逻辑完全一致,语法稍有差异:

绑定事件

Public Sub New()
    InitializeComponent()
    AddHandler DataGridView1.CellFormatting, AddressOf DataGridView1_CellFormatting
End Sub

事件处理逻辑

Private Sub DataGridView1_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs)
    If DataGridView1.Columns(e.ColumnIndex).Name = "Date" AndAlso e.RowIndex <> DataGridView1.NewRowIndex Then
        Dim rowDate As DateTime
        If DateTime.TryParse(e.Value?.ToString(), rowDate) Then
            Dim today As DateTime = DateTime.Today
            Dim daysRemaining As Integer = CInt((rowDate.Date - today.Date).TotalDays)
            Dim currentRow As DataGridViewRow = DataGridView1.Rows(e.RowIndex)
            
            If daysRemaining <= 1 Then
                currentRow.DefaultCellStyle.BackColor = Color.Red
            ElseIf daysRemaining <= 5 Then
                currentRow.DefaultCellStyle.BackColor = Color.Orange
            Else
                currentRow.DefaultCellStyle.BackColor = DataGridView1.DefaultCellStyle.BackColor
            End If
        End If
    End If
End Sub

关键注意事项

  • 跳过新增行:判断e.RowIndex != dataGridView1.NewRowIndex,避免对底部的空白新增行应用样式
  • 安全解析日期:用DateTime.TryParse而非强制转换,防止单元格值不是有效日期时抛出异常
  • 清除旧样式:剩余天数超过15天时恢复默认背景色,避免排序或刷新后旧样式残留到其他行
  • 优化性能:如果Date列绑定的是DateTime类型(不是字符串),可以直接用DateTime rowDate = (DateTime)e.Value;替代TryParse,提升运行效率

内容的提问来源于stack exchange,提问作者Rahim Ben's

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 09:07:49