Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataGridView Preserve Selected Index and Scroll Position after update and reload

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?

like image 639
sokol Avatar asked Dec 11 '22 18:12

sokol


2 Answers

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

int index = dataGridView1.CurrentRow.Index;

/*
 * Your Refresh Code
 */

dataGridView1.FirstDisplayedScrollingRowIndex = index;
like image 69
OhBeWise Avatar answered Jan 04 '23 23:01

OhBeWise


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:

  • To scroll and set the current row, set CurrentCell.
  • To only scroll, set FirstDisplayedScrollingRowIndex.

Scroll And set current row:

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

Scroll:

dataGridView1.FirstDisplayedScrollingRowIndex = currentIndex;
like image 26
Reza Aghaei Avatar answered Jan 05 '23 00:01

Reza Aghaei