5

I have some problem, don't now how to preserve the scroll position in a DataGridView.

I have over 1000+ rows and scrolling back to edited row is painful. How can I preserve the scroll position and scroll to the edited row after refreshing data?

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
sokol
  • 79
  • 1
  • 1
  • 4

3 Answers3

9

Save the row index, do your refresh, then set the FirstDisplayedScrollingRowIndex property.

int index = dataGridView1.CurrentRow.Index;

/*
 * Your Refresh Code
 */

dataGridView1.FirstDisplayedScrollingRowIndex = index;
OhBeWise
  • 5,350
  • 3
  • 32
  • 60
  • This code works but before scrolling to last scrolling position, scrollbar jumps to top for a fraction of second. I don't know how to deal with it. – Nirav Parsana Jul 15 '19 at 09:52
  • 2
    @NiravParsana I am unable to test this currently, but perhaps try wrapping this code in `dataGridView1.SuspendLayout()` and `.ResumeLayout()`. If not that, maybe something else [to suspend the grid](https://stackoverflow.com/q/4649995/3773066) will work? – OhBeWise Jul 15 '19 at 18:12
5

You can get the current row index before reloading data:

int currentIndex= dataGridView1.CurrentRow.Index;

Then after reloading data, you can use either of these options:

Scroll And set current row:

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

Scroll:

dataGridView1.FirstDisplayedScrollingRowIndex = currentIndex;
Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
0
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;
}
Proz
  • 1
  • 1
  • This is still a little choppy because the user loses focus of the scroll bar when updating, but it works – Proz Feb 04 '21 at 09:46