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

VB中DataGridView自定义行背景色排序后重置为白色如何解决

问题原因

排序操作会触发DataGridView的行重绘与数据重绑定,你仅单次调用ColorRows设置的行样式会被默认样式覆盖,因此背景色会重置为白色。

解决方案

方案1(推荐):使用 CellFormatting 事件自动应用样式

这是WinForm DataGridView自定义样式的官方推荐实现,只要单元格需要刷新(包括排序、滚动、编辑单元格、新增行等场景)就会自动触发,样式不会丢失:

Private Sub DataGridView1_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
    ' 跳过列头行和新行
    If e.RowIndex < 0 OrElse DataGridView1.Rows(e.RowIndex).IsNewRow Then
        Return
    End If
    Dim row = DataGridView1.Rows(e.RowIndex)
    ' 先重置背景色避免样式残留
    row.DefaultCellStyle.BackColor = Color.White
    
    ' 判断已完成状态
    If row.Cells("Done").Value IsNot DBNull.Value Then
        row.DefaultCellStyle.BackColor = Color.PaleGreen
    ' 判断有备注且未完成状态
    ElseIf row.Cells("Note").Value IsNot DBNull.Value Then
        row.DefaultCellStyle.BackColor = Color.NavajoWhite
    End If
End Sub

你可以直接删除原有手动调用的ColorRows方法,不需要再主动调用这段逻辑。

方案2:保留原有逻辑,排序后重新触发样式设置

如果你不想修改原有ColorRows的实现,只需要为DataGridView的Sorted事件添加处理,排序完成后自动重新执行样式设置即可:

Private Sub DataGridView1_Sorted(sender As Object, e As EventArgs) Handles DataGridView1.Sorted
    ColorRows()
End Sub

补充说明:如果需要编辑单元格内容后自动更新颜色,还需要额外处理CellEndEdit事件,同样在事件内调用ColorRows即可。

内容的提问来源于stack exchange,提问作者LM Rig

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 11:45:03