DataGridView 在更新和重新加载后保留选定的索引和滚动位置
DataGridView Preserve Selected Index and Scroll Position after update and reload
我有一些问题,现在不知道如何在 DataGridView
中保留滚动位置。
我有超过 1000 多行,滚动回已编辑的行很痛苦。如何在刷新数据后保留滚动位置并滚动到编辑行?
保存行索引,进行刷新,然后设置 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;
}
我有一些问题,现在不知道如何在 DataGridView
中保留滚动位置。
我有超过 1000 多行,滚动回已编辑的行很痛苦。如何在刷新数据后保留滚动位置并滚动到编辑行?
保存行索引,进行刷新,然后设置 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;
}