DataGridView在更新和重新加载后保留所选索引和滚动位置

本文关键字:保留 索引 位置 滚动 加载 更新 新加载 DataGridView | 更新日期: 2023-09-27 18:30:09

我有一些问题,现在不知道如何在DataGridView中保留滚动位置。

我有1000多行,滚动回编辑过的行很痛苦。刷新数据后,如何保留滚动位置并滚动到编辑行?

DataGridView在更新和重新加载后保留所选索引和滚动位置

保存行索引,进行刷新,然后设置FirstDisplayedScrollingRowIndex属性。

int index = dataGridView1.CurrentRow.Index;
/*
 * Your Refresh Code
 */
dataGridView1.FirstDisplayedScrollingRowIndex = index;

您可以在重新加载数据之前获得当前行索引:

int currentIndex= dataGridView1.CurrentRow.Index;

然后在重新加载数据后,您可以使用以下任一选项:

  • 要滚动并设置当前行,请设置CurrentCell
  • 要仅滚动,请设置FirstDisplayedScrollingRowIndex

滚动并设置当前行:

this.dataGridView1.CurrentCell =  this.DataGridView1.Rows[currentIndex].Cells[0];

滚动:

dataGridView1.FirstDisplayedScrollingRowIndex = currentIndex;
void SomeMethod()
{
    if (dataGridView != null &&
        dataGridView.CurrentRow != null)
            this.Invoke(new Action(GetScrollingIndex));
    UpdateTable();
    if (dataGridView != null &&
        dataGridView.CurrentRow != null)
            this.Invoke(new Action(SetScrollingIndex));
}
void GetScrollingIndex()
{
    scrollingIndex = dataGridView.FirstDisplayedCell.RowIndex;
}
    
void SetScrollingIndex()
{
    dataGridView.FirstDisplayedScrollingRowIndex = scrollingIndex;
}