Selected DataGridView row is being overwritten (me

2019-08-31 07:28发布

So I have a DataGridView with 56 rows of data in it. When I select any row, then scroll it off the screen and then back on again, the original data from the selected row becomes merged with the data of another row - seems to depend on whether I scroll up/down or use scrollbar or mouse wheel (I suspect pgUp/Down and arrow keys will have a similar effect also). Searching the web only produced one result of a similar situation when the user scrolled horizontally... it was suggested he use Double Buffering, but the Reflection based code only caused my selected row to turn totally black:

Imports System.Reflection

Module DataGridViewExtensions
    <System.Diagnostics.DebuggerStepThrough()> _
     <System.Runtime.CompilerServices.Extension()> _
    Public Sub DoubleBuffered(ByVal sender As DataGridView, ByVal Setting As Boolean)
        Dim dgvType As Type = sender.[GetType]()
        Dim pi As PropertyInfo = dgvType.GetProperty("DoubleBuffered", BindingFlags.Instance Or BindingFlags.NonPublic)
        pi.SetValue(sender, Setting, Nothing)
    End Sub
End Module

I have tried setting the DGV VirtualMode to true and false and neither makes a difference. Any insight would be great!

1条回答
别忘想泡老子
2楼-- · 2019-08-31 08:21

Ok, so this may not be the definitive answer but points me in the right direction... was having other issues with the DGV - when the DGV was initially shown, the first row was being selected and "overwriting" the background colour in white... found this code to fix the background colour issue and it solved the text overwriting issue:

Private Sub dgvPicks_CellFormatting(sender As Object, e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles dgvPicks.CellFormatting
    If e.ColumnIndex = 0 Then
        e.CellStyle.SelectionBackColor = SystemColors.Highlight
        e.CellStyle.SelectionForeColor = Color.White
    Else
        e.CellStyle.SelectionBackColor = e.CellStyle.BackColor
        e.CellStyle.SelectionForeColor = e.CellStyle.ForeColor
    End If
End Sub

Not sure if it specifically has to do with properly setting the SelectionBackColor or has to do with using the CellFormatting event, but this code killed two birds with one stone! I found the code from this article which may provide more insight: Implementing a transparent row selection in a DataGridView control

查看更多
登录 后发表回答