如何在winforms应用程序中设置数据网格滚动条的位置?

在我的C#winforms应用程序中,我有一个数据网格。 当datagrid重新加载时,我想将滚动条设置回用户设置的位置。 我怎样才能做到这一点?

编辑:我正在使用旧的winforms DataGrid控件,而不是较新的DataGridView

您实际上并不直接与滚动条进行交互,而是设置FirstDisplayedScrollingRowIndex 。 因此,在重新加载之前,捕获该索引,一旦重新加载,将其重置为该索引。

编辑:评论中的好点。 如果您正在使用DataGridView那么这将有效。 如果您使用旧的DataGrid那么最简单的方法就是inheritance它。 看到这里: 联系

DataGrid具有受保护的GridVScrolled方法,可用于将网格滚动到特定行。 要使用它,从DataGrid派生一个新网格并添加一个ScrollToRow方法。

C#代码

 public void ScrollToRow(int theRow) { // // Expose the protected GridVScrolled method allowing you // to programmatically scroll the grid to a particular row. // if (DataSource != null) { GridVScrolled(this, new ScrollEventArgs(ScrollEventType.LargeIncrement, theRow)); } } 

是的,绝对是FirstDisplayedScrollingRowIndex 。 您需要在一些用户交互后捕获此值,然后在网格重新加载后,您将要将其设置回旧值。

例如,如果通过单击按钮触发重新加载,则在按钮单击处理程序中,您可能希望将第一行作为将此值放入变量的命令:

 // Get current user scroll position int scrollPosition = myGridView.FirstDisplayedScrollingRowIndex; // Do some work ... // Rebind the grid and reset scrolling myGridView.DataBind; myGridView.FirstDisplayedScrollingRowIndex = scrollPosition; 

刚刚在BFree给出的链接上发布了答案

DataGrid具有受保护的GridVScrolled方法,可用于将网格滚动到特定行。 要使用它,从DataGrid派生一个新网格并添加一个ScrollToRow方法。

C#代码

 public void ScrollToRow(int theRow) { // // Expose the protected GridVScrolled method allowing you // to programmatically scroll the grid to a particular row. // if (DataSource != null) { GridVScrolled(this, new ScrollEventArgs(ScrollEventType.LargeIncrement, theRow)); } } 

VB.NET代码

 Public Sub ScrollToRow(ByVal theRow As Integer) ' ' Expose the protected GridVScrolled method allowing you ' to programmatically scroll the grid to a particular row. ' On Error Resume Next If Not DataSource Is Nothing Then GridVScrolled(Me, New ScrollEventArgs(ScrollEventType.LargeIncrement, theRow)) End If End Sub 

将垂直和水平滚动值存储到某个变量中并重置它们。

 int v= dataGridView1.VerticalScrollingOffset ; int h= dataGridView1.HorizontalScrollingOffset ; //...reload dataGridView1.VerticalScrollingOffset = v; dataGridView1.HorizontalScrollingOffset =h; 

我使用@BFree的答案,但也需要捕获DataGrid的第一个可见行:

 int indexOfTopMostRow = HitTest(dataGrid.RowHeaderWidth + 10, dataGrid.PreferredRowHeight + 10).Row; 

即使这是一个老问题,上面的许多解决方案对我来说都不起作用。 最终起作用的是:

 if(gridEmployees.FirstDisplayedScrollingRowIndex != -1) gridEmployees.FirstDisplayedScrollingRowIndex = 0;