datagridview单元格合并

本文分享了一个解决DataGridView单元格合并后无法让内容居中显示的技巧,通过清除单元格背景并画出网格边线,实现真正意义上的合并效果。适合在Windows应用程序开发中使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近遇到一个比较棘手的问题那就是对datagridview进行单元格合并的处理,在网上找了很久合并的问题倒是解决了!不过合并后却无法让内容居中显示!经过苦思冥想发现是这个合并的方法有问题,他紧紧是把边缘线去掉并没有完成真证意义上的合并!现在把此方法分享给大家,希望各位大虾能补充补充!

 Private Sub DataGridView1_CellPainting(ByVal sender As System.Object, ByVal e As DataGridViewCellPaintingEventArgs) Handles DataGridView1.CellPainting
        ' 合并
        If e.ColumnIndex >= 0 AndAlso e.RowIndex <> -1 Then
            Using gridBrush As Brush = New SolidBrush(Me.DataGridView1.GridColor), backColorBrush As Brush = New SolidBrush(e.CellStyle.BackColor)
                Using gridLinePen As New Pen(gridBrush)
                    ' 清除单元格
                    e.Graphics.FillRectangle(backColorBrush, e.CellBounds)
                    ' 画 Grid 边线(仅画单元格的底边线和右边线)
                    ' 如果下一行和当前行的数据不同,则在当前的单元格画一条底边线
                    If e.RowIndex < DataGridView1.Rows.Count - 1 AndAlso DataGridView1.Rows(e.RowIndex + 1).Cells(e.ColumnIndex).Value.ToString() <> e.Value.ToString() Then
                        e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left, e.CellBounds.Bottom - 1, e.CellBounds.Right - 1, e.CellBounds.Bottom - 1)
                        wx = 0
                    Else
                        wx = wx + e.CellBounds.Width
                    End If
                    ' 画右边线
                    If e.ColumnIndex < DataGridView1.Columns.Count - 1 AndAlso DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex + 1).Value.ToString() <> e.Value.ToString() Then
                        e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1, e.CellBounds.Top, e.CellBounds.Right - 1, e.CellBounds.Bottom)
                        hy = 0
                    Else
                        hy = hy + e.CellBounds.Height
                    End If
                    ' 画(填写)单元格内容,相同的内容的单元格只填写第一个
                    If e.Value IsNot Nothing Then
                        If (e.RowIndex > 0 AndAlso DataGridView1.Rows(e.RowIndex - 1).Cells(e.ColumnIndex).Value.ToString() = e.Value.ToString()) Or (e.ColumnIndex > 0 AndAlso DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex - 1).Value.ToString() = e.Value.ToString) Then
                        Else
                            e.Graphics.DrawString(DirectCast(e.Value, [String]), e.CellStyle.Font, Brushes.Black, e.CellBounds.X + 50, e.CellBounds.Y + 5, StringFormat.GenericDefault)
                        End If
                    End If
                    e.Handled = True
                End Using
            End Using
        End If

end sub

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值