Hi!
I'm merging all cells of a row in a DataGridView. However, when i click on or select a merged cell, the display is flawed:
Public Class Form1
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
With DataGridView1
.Columns.Add("Col1", "Col1")
.Columns.Add("Col2", "Col2")
.Columns.Add("Col3", "Col3")
.Columns.Add("Col4", "Col4")
.Rows.Add("", "", "", "TitleTitleTitleTitleTitleTitle")
.Rows.Add("Col1", "Col2", "Col3", "Col4")
.Rows.Add("Col1", "Col2", "Col3", "Col4")
.Rows.Add("Col1", "Col2", "Col3", "Col4")
.Rows.Add("", "", "", "TitleTitleTitleTitleTitleTitle")
.Rows.Add("Col1", "Col2", "Col3", "Col4")
.Rows.Add("Col1", "Col2", "Col3", "Col4")
.RowHeadersVisible = False
.ReadOnly = True
.SelectionMode = DataGridViewSelectionMode.FullRowSelect
.AllowUserToResizeRows = False
End With
End Sub
Private Sub DataGridView1_RowPrePaint(sender As Object, e As System.Windows.Forms.DataGridViewRowPrePaintEventArgs) Handles DataGridView1.RowPrePaint
If e.RowIndex = 0 OrElse e.RowIndex = 4 Then
DataGridView1.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.CadetBlue
End If
End Sub
Private Sub DataGridView1_CellPainting(sender As Object, e As System.Windows.Forms.DataGridViewCellPaintingEventArgs) Handles DataGridView1.CellPainting
If e.RowIndex = 0 OrElse e.RowIndex = 4 Then
Dim gridBrush As Brush = New SolidBrush(DataGridView1.GridColor)
Dim backColorBrush As Brush = New SolidBrush(e.CellStyle.BackColor)
Dim gridLinePen As Pen = New Pen(gridBrush)
e.Graphics.FillRectangle(backColorBrush, e.CellBounds)
If e.ColumnIndex = 3 Then
e.Graphics.DrawString(CType(e.Value, String),
e.CellStyle.Font, Brushes.Black,
4, Convert.ToSingle(e.CellBounds.Y + 4))
End If
e.Handled = True
End If
End Sub
End Class
If I add "Invalidate" as follows it seems to work. However, is there a better way to make it work?
Private Sub DataGridView1_MouseDown(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles DataGridView1.MouseDown
DataGridView1.Invalidate()
End Sub
Private Sub DataGridView1_CellClick(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellClick
DataGridView1.Invalidate()
End Sub
Private Sub DataGridView1_SelectionChanged(sender As Object, e As System.EventArgs) Handles DataGridView1.SelectionChanged
DataGridView1.Invalidate()
End Sub
Private Sub DataGridView1_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles DataGridView1.KeyDown
DataGridView1.Invalidate()
End Sub
Private Sub DataGridView1_CellDoubleClick(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellDoubleClick
DataGridView1.Invalidate()
End Sub