DataGridView 真·列头不高亮 & 真·列头合并

文章介绍了在VB.Net的WinForm环境下,使用DataGridView时遇到的列头高亮显示问题,以及在.NETFramework4.8中,常规的解决方法如设置ColumnHeadersDefaultCellStyle无效。作者提供了一个真·解决方式,即通过在CellPainting事件中进行自绘,同时实现了列头合并功能。文章还详细展示了如何处理滚动时的显示问题,并对比了不同实现方式的效果。
摘要由CSDN通过智能技术生成

高亮BUG

VB.Net,在 .NET Framework 4.8 的 WinForm 下(即不是 WPF 的绘图模式、也不是 Core 或 Mono 的开发框架),使用 DataGridView 行模式,还是有个列头表现为高亮显示:
默认行模式
查找各种解决方式:

  • 设置 ColumnHeadersDefaultCellStyle ———— 无效
  • 直接修改每列的 HeaderCell.Style ———— 无效

既然有上述"解决方式",说明早期版本是有效的。至于从哪个版本开始无效,就不深究了,反正碰上了如下解决。

真·解决方式

只能在 CellPainting 事件中进行自绘了,顺便实现了列头合并功能(不需要多行列头)。

  1. 添加一个RowDataGridView用户控件,集成不需要设计,关掉直接改代码。
  2. RowDataGridView.Designer.vb 按注释修改
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class RowDataGridView
    Inherits System.Windows.Forms.DataGridView                      '<- 原先是 UserControl

    'UserControl 重写释放以清理组件列表。
    <System.Diagnostics.DebuggerNonUserCode()> _
    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
        Try
            If disposing AndAlso components IsNot Nothing Then
                components.Dispose()
            End If
        Finally
            MyBase.Dispose(disposing)
        End Try
    End Sub

    'Windows 窗体设计器所必需的
    Private components As System.ComponentModel.IContainer

    '注意: 以下过程是 Windows 窗体设计器所必需的
    '可以使用 Windows 窗体设计器修改它。  
    '不要使用代码编辑器修改它。
    <System.Diagnostics.DebuggerStepThrough()> _
    Private Sub InitializeComponent()
        components = New System.ComponentModel.Container()
        Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font  '<- 编译错误,删除该行
    End Sub

End Class
  1. RowDataGridView.vb
Public Class RowDataGridView

    Private m_ColHeadersSpan() As String

    ''' <summary>列头合并</summary>
    ''' <remarks>务必在定义<see cref="Columns"/>后修改。合并设置仅按次序、不随列定义同步调整。</remarks>
    ''' <returns>每列格式:
    ''' <list type="bullet">
    ''' <description>数值后的注释仅供参考</description>
    ''' <description>数值 1: (默认)非合并列头</description>
    ''' <description>数值 0: 被合并列头</description>
    ''' <description>其他正整数: 合并开始列头</description>
    ''' </list>
    ''' ☆ 数值正确性不检查。
    ''' ☆ 合并不影响自动列宽计算(即标题可能撑开合并开始列)。</returns>
    Public Property ColHeadersSpan() As String()
        Get
            If Me.ColumnCount > 0 Then
                Dim lastCount As Integer
                If m_ColHeadersSpan Is Nothing Then
                    lastCount = 0
                 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值