Windows窗体:禁用DataGridView上的自动滚动

时间:2017-02-02 15:14:44

标签: vb.net winforms datagridview .net-4.5

我有一个DataGridView,我不断用BackgroundWorker添加行。

问题在于,即使每行都添加到DataGridView的底部,滚动条也会继续向上移动而不是剩余 在我之前搬过它的同一个地方。

如何禁用自动滚动,以便在底部添加新行时将DataGridView保持在同一位置?

2 个答案:

答案 0 :(得分:0)

我通常使用ListView执行此操作,并且我确信DataGridView的工作方式类似:

If ListView1.Items.Count > 0 Then

    ListView1.Items.Item(ListView1.Items.Count -1).EnsureVisible()

End If

这将确保您的上一个条目可见。

答案 1 :(得分:0)

您可以使用 DataGridView1_Scroll 事件来获取特定的滚动位置。如下 -

 Dim savedScrollPosition As Integer = 0
    Private Sub DataGridView1_Scroll(sender As Object, e As System.Windows.Forms.ScrollEventArgs) Handles DataGridView1.Scroll
    savedScrollPosition = e.NewValue
End Sub

然后,您可以在添加新行后将其分配给DataGridView属性 FirstDisplayedScrollingRowIndex 。如下 -

Public Class Form1

Dim i As Integer = 1
Dim savedScrollPosition As Integer = 0

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    Dim timer As New Timer()
    timer.Interval = 1000
    AddHandler timer.Tick, AddressOf timer_Tick
    timer.Start()    
End Sub

Private Sub timer_Tick(ByVal sender As Object, ByVal e As EventArgs)
    UpdateDGV()
    i = i + 1
End Sub

Private Sub UpdateDGV()
    DataGridView1.ColumnCount = 2
    DataGridView1.Columns(0).Name = "Product_Name"
    DataGridView1.Columns(1).Name = "Product_Price"

    Dim row As String() = New String() {"Product # " + Convert.ToString(i), 1000 + i}
    DataGridView1.Rows.Add(row)

    'Keep your scrollbar at specific position
    DataGridView1.FirstDisplayedScrollingRowIndex = savedScrollPosition

    'keep your scrollbar at bottom of the grid
    'DataGridView1.FirstDisplayedScrollingRowIndex = DataGridView1.RowCount - 1

End Sub

Private Sub DataGridView1_Scroll(sender As Object, e As System.Windows.Forms.ScrollEventArgs) Handles DataGridView1.Scroll
    savedScrollPosition = e.NewValue
End Sub
End Class