最近遇到一个比较棘手的问题那就是对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