You need to enable JavaScript to run this app. 加载时如何根据条件设置DataGridView行的FontStyle字体样式
优惠活动
大模型
产品
解决方案
定价
更多

加载时如何根据条件设置DataGridView行的FontStyle字体样式

DataGridView按条件设置行字体样式的正确实现

原代码存在的问题

  • 仅处理了当前选中行,没有遍历所有行,不符合修改所有行的需求
  • 修改的是控件全局的DefaultCellStyle属性,会覆盖所有行的样式,无法实现单行单独控制
  • 循环遍历所有列是无效操作,判断逻辑仅依赖索引为4的列,每行只需判断1次即可
  • 无返回值的逻辑错误使用Function定义,应该用无返回值的Sub
  • 没有处理单元格空值(DBNull)的情况,可能触发运行时异常

推荐实现方案:使用CellFormatting事件

该事件会在单元格需要渲染时自动触发,无需手动调用,数据绑定、滚动刷新时都会自动应用样式,性能更优。

Private Sub DetailDataGridView_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles DetailDataGridView.CellFormatting
    ' 只处理数据行,跳过表头行
    If e.RowIndex < 0 OrElse e.RowIndex >= DetailDataGridView.RowCount Then Exit Sub
    
    Dim targetCell = DetailDataGridView.Item(4, e.RowIndex)
    ' 先判断单元格值不为空
    If targetCell.Value IsNot Nothing AndAlso Not IsDBNull(targetCell.Value) Then
        Dim cellVal As Integer = CInt(targetCell.Value)
        If cellVal = 0 Then
            DetailDataGridView.Rows(e.RowIndex).DefaultCellStyle.Font = New Font("ARIAL", 8, FontStyle.Strikeout)
        Else
            DetailDataGridView.Rows(e.RowIndex).DefaultCellStyle.Font = New Font("ARIAL", 8, FontStyle.Regular)
        End If
    Else
        ' 空值默认用常规样式
        DetailDataGridView.Rows(e.RowIndex).DefaultCellStyle.Font = New Font("ARIAL", 8, FontStyle.Regular)
    End If
End Sub

手动调用的实现方案(对应原有逻辑的修改版)

如果需要手动触发样式刷新,可以使用以下方法:

Private Sub DetailGridViewSetStyle()
    Dim dgv As DataGridView = DetailDataGridView
    ' 遍历所有行
    For rowInd As Integer = 0 To dgv.RowCount - 1
        ' 跳过新行模板(如果控件允许添加行的话)
        If dgv.Rows(rowInd).IsNewRow Then Continue For
        
        Dim targetCell = dgv.Item(4, rowInd)
        If targetCell.Value IsNot Nothing AndAlso Not IsDBNull(targetCell.Value) Then
            Dim cellVal As Integer = CInt(targetCell.Value)
            If cellVal = 0 Then
                dgv.Rows(rowInd).DefaultCellStyle.Font = New Font("ARIAL", 8, FontStyle.Strikeout)
            Else
                dgv.Rows(rowInd).DefaultCellStyle.Font = New Font("ARIAL", 8, FontStyle.Regular)
            End If
        Else
            dgv.Rows(rowInd).DefaultCellStyle.Font = New Font("ARIAL", 8, FontStyle.Regular)
        End If
    Next
End Sub

内容的提问来源于stack exchange,提问作者Waqar Yousufzai

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 18:33:02