You need to enable JavaScript to run this app. VB.NET实现DataGridView列分组时报错Type GridViewRow is not defined如何解决
优惠活动
大模型
产品
解决方案
定价
更多

VB.NET实现DataGridView列分组时报错Type GridViewRow is not defined如何解决

错误原因
  1. 控件API不匹配
    你当前使用的代码是针对ASP.NET Web Forms的GridView控件编写的,而你实际在用的是WinForm的DataGridView控件,二者行对象类型完全不同:
  • ASP.NET GridView的行类型是GridViewRow
  • WinForm DataGridView的行类型是DataGridViewRow
    你当前项目未引入ASP.NET相关命名空间,自然会抛出Type GridViewRow is not defined的错误。
  1. 逻辑不兼容
    即便强行引入ASP.NET命名空间,这段代码也无法在DataGridView上运行,两个控件的单元格属性、合并逻辑的API规则完全不同,必须针对性修改适配。
适配WinForm DataGridView的合并代码
Protected Sub MergeDuplicateCells()
    ' 从下往上遍历所有行,跳过表头行
    For i As Integer = SearchInvoiceDGV.Rows.Count - 1 To 1 Step -1
        Dim currentRow As DataGridViewRow = SearchInvoiceDGV.Rows(i)
        Dim prevRow As DataGridViewRow = SearchInvoiceDGV.Rows(i - 1)
        ' 遍历所有列
        For j As Integer = 0 To currentRow.Cells.Count - 1
            ' 比较相邻行同一列的内容
            If currentRow.Cells(j).Value?.ToString() = prevRow.Cells(j).Value?.ToString() Then
                ' 用Tag属性存储合并跨度
                If prevRow.Cells(j).Tag Is Nothing Then
                    prevRow.Cells(j).Tag = 1
                End If
                prevRow.Cells(j).Tag = CInt(prevRow.Cells(j).Tag) + 1
                ' 隐藏重复的单元格
                currentRow.Cells(j).Visible = False
            End If
        Next
    Next
End Sub

' 自定义绘制合并单元格,保证内容居中显示完整
Protected Sub SearchInvoiceDGV_CellPainting(sender As Object, e As DataGridViewCellPaintingEventArgs) Handles SearchInvoiceDGV.CellPainting
    If e.RowIndex < 0 OrElse e.ColumnIndex < 0 Then Return
    Dim targetCell = SearchInvoiceDGV.Rows(e.RowIndex).Cells(e.ColumnIndex)
    If targetCell.Tag IsNot Nothing AndAlso CInt(targetCell.Tag) > 1 Then
        ' 去掉合并单元格的下边框
        e.AdvancedBorderStyle.Bottom = DataGridViewAdvancedCellBorderStyle.None
        ' 计算合并后的总高度
        Dim totalHeight As Integer = e.CellBounds.Height
        For spanIndex As Integer = 1 To CInt(targetCell.Tag) - 1
            totalHeight += SearchInvoiceDGV.Rows(e.RowIndex + spanIndex).Height
        Next
        ' 绘制合并后的单元格
        Dim mergeRect As New Rectangle(e.CellBounds.X, e.CellBounds.Y, e.CellBounds.Width, totalHeight)
        e.PaintBackground(mergeRect, True)
        e.PaintContent(mergeRect)
        e.Handled = True
    End If
End Sub
使用说明
  • 如果只需要合并指定列,修改内层循环j的遍历范围到目标列的索引即可
  • 在DataGridView完成数据绑定后,手动调用MergeDuplicateCells()即可触发合并效果

内容的提问来源于stack exchange,提问作者Point Systems

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 02:45:01