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

ReasonsGridView_CellFormatting事件导致DataGridView显示异常

ReasonsGridView_CellFormatting事件导致DataGridView显示异常

兄弟,我看你遇到的这个DataGridView滚动后显示混乱的问题,大概率是CellFormatting事件的触发逻辑和DataGridView的行复用机制冲突了。

你现在的代码只在第25列被格式化的时候才设置整行背景色,但DataGridView为了提升性能,会复用那些滚出视野的行来渲染新进入视野的行。这就会导致:如果某行复用了之前被设置过颜色的行,而此时第25列没有触发格式化(比如滚动时优先绘制其他列),那这个复用的行就会带着之前的颜色,出现显示异常。而且你没处理值为空的情况,一旦复用的行第25列值为空,背景色不会被重置,残留的旧颜色就会乱套。

给你两个修正方案:

方案一:调整CellFormatting事件逻辑

不管当前格式化的是哪一列,都检查当前行第25列的颜色值,同时处理值为空的情况,重置回默认背景色:

private void ReasonsGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    // 确保是有效行索引
    if (e.RowIndex < 0 || e.RowIndex >= ReasonsGridView.Rows.Count)
        return;
        
    DataGridViewRow currentRow = ReasonsGridView.Rows[e.RowIndex];
    object colorValue = currentRow.Cells[25].Value;
    
    if (colorValue != null && colorValue is Color)
    {
        currentRow.DefaultCellStyle.BackColor = (Color)colorValue;
    }
    else
    {
        // 重置为DataGridView默认背景色,避免复用行残留颜色
        currentRow.DefaultCellStyle.BackColor = ReasonsGridView.DefaultCellStyle.BackColor;
    }
}

方案二:改用RowPrePaint事件

RowPrePaint是在行绘制前触发的,针对整行操作,逻辑更清晰,也更适合设置整行样式:

private void ReasonsGridView_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
{
    // 排除新行和无效行
    if (e.RowIndex < 0 || e.RowIndex >= ReasonsGridView.Rows.Count || ReasonsGridView.Rows[e.RowIndex].IsNewRow)
        return;
        
    DataGridViewRow currentRow = ReasonsGridView.Rows[e.RowIndex];
    object colorValue = currentRow.Cells[25].Value;
    
    if (colorValue != null && colorValue is Color)
    {
        currentRow.DefaultCellStyle.BackColor = (Color)colorValue;
    }
    else
    {
        currentRow.DefaultCellStyle.BackColor = ReasonsGridView.DefaultCellStyle.BackColor;
    }
}

另外要注意:确保第25列的单元格确实存储的是Color类型的值,避免类型转换异常。这样调整后,滚动时行的背景色就会正确更新,不会再出现混乱的情况了。

备注:内容来源于stack exchange,提问作者ratboybyron

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.15 12:43:03