在我的 C# winforms 应用程序中,我有一个数据网格。当数据网格重新加载时,我想将滚动条设置回用户设置的位置。我怎样才能做到这一点?
编辑:我使用的是旧的 winforms DataGrid 控件,而不是较新的 DataGridView
您实际上并不直接与滚动条交互,而是将FirstDisplayedScrollingRowIndex
. 因此,在重新加载之前,捕获该索引,一旦重新加载,将其重置为该索引。
编辑:评论中的好点。如果您使用的是 aDataGridView
那么这将起作用。如果您使用的是旧DataGrid
的,那么最简单的方法就是继承它。见这里:联动
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;
将您的垂直和水平滚动值存储到某个变量中并重置它们。
int v= dataGridView1.VerticalScrollingOffset ;
int h= dataGridView1.HorizontalScrollingOffset ;
//...reload
dataGridView1.VerticalScrollingOffset = v;
dataGridView1.HorizontalScrollingOffset =h;
刚刚在给出的链接上发布了答案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 Scroll;
void DataGridView1Scroll(object sender, ScrollEventArgs e)
{
Scroll = dataGridView1.VerticalScrollingOffset;
}
并且您可以在刷新后将 dgv 的滚动设置到相同的位置,加载 dgv... 使用下一个代码:
PropertyInfo verticalOffset = dataGridView1.GetType().GetProperty("VerticalOffset", BindingFlags.NonPublic |
BindingFlags.Instance);
verticalOffset.SetValue(this.dataGridView1, Scroll, null);
我使用了@BFree 的答案,但还需要捕获第一个可见行DataGrid
:
int indexOfTopMostRow = HitTest(dataGrid.RowHeaderWidth + 10,
dataGrid.PreferredRowHeight + 10).Row;
尽管这是一个老问题,但上面的许多解决方案都对我不起作用。最终奏效的是:
if(gridEmployees.FirstDisplayedScrollingRowIndex != -1) gridEmployees.FirstDisplayedScrollingRowIndex = 0;