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

如何基于有效期过期判断条件修改DataGridView的行颜色

实现代码及逻辑说明

你原有代码的逻辑存在误区:CellFormatting 事件会在每个单元格需要渲染时自动触发,无需在事件内遍历所有行,直接操作当前触发事件对应的行即可,完整实现代码如下:

private void ViewMedicine_DataGrid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    // 过滤表头行、新增空白行,只处理正式数据行
    if (e.RowIndex < 0 || ViewMedicine_DataGrid.Rows[e.RowIndex].IsNewRow)
        return;

    // 此处将"ExpiryDate"替换为你数据源中有效期对应的字段名称
    object expiryDateObj = ViewMedicine_DataGrid.Rows[e.RowIndex].Cells["ExpiryDate"].Value;
    // 空值/非法日期格式直接跳过处理,避免报错
    if (expiryDateObj == null || !DateTime.TryParse(expiryDateObj.ToString(), out DateTime expiryDate))
        return;

    TimeSpan remainingDays = expiryDate.Date - DateTime.Now.Date;

    // 已过期:有效期早于当前日期
    if (remainingDays.TotalDays < 0)
    {
        ViewMedicine_DataGrid.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red;
        ViewMedicine_DataGrid.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.White;
    }
    // 距离到期不足30天
    else if (remainingDays.TotalDays < 30)
    {
        ViewMedicine_DataGrid.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Yellow;
        ViewMedicine_DataGrid.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.Black;
    }
    // 正常有效期恢复默认样式,避免滚动时样式复用错乱
    else
    {
        ViewMedicine_DataGrid.Rows[e.RowIndex].DefaultCellStyle.BackColor = ViewMedicine_DataGrid.DefaultCellStyle.BackColor;
        ViewMedicine_DataGrid.Rows[e.RowIndex].DefaultCellStyle.ForeColor = ViewMedicine_DataGrid.DefaultCellStyle.ForeColor;
    }
}

核心判断逻辑说明

注:你的问题描述中写的「有效期大于当前日期即已过期」属于笔误,代码按正常业务逻辑(有效期早于当前日期为过期)实现,如果确实需要适配你描述的反向逻辑,调整判断符号即可。

  • 先校验行索引合法性,排除表头和新增空白行
  • 取出有效期字段值后做类型转换,空值/非法格式直接跳过处理避免报错
  • 计算有效期和当前日期的差值:
    • 差值总天数小于0:已过期,对应红底白字样式
    • 差值总天数大于等于0且小于30:即将到期,对应黄底样式
    • 其余情况恢复默认样式,避免滚动DataGridView时出现样式复用的错乱问题

内容的提问来源于stack exchange,提问作者Omer Butt

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 15:15:03