DataGridView: how to make scrollbar in sync with current cell selection?

Posted by David.Chu.ca on Stack Overflow See other posts from Stack Overflow or by David.Chu.ca
Published on 2010-06-02T22:15:12Z Indexed on 2010/06/05 16:52 UTC
Read the original article Hit count: 326

I have a windows application with DataGridView as data presentation. Every 2 minutes, the grid will be refreshed with new data. In order to keep the scroll bar in sync with the new data added, I have to reset its ScrollBars:

dbv.Rows.Clear(); // clear rows
SCrollBars sc = dbv.ScrollBars;
dbv.ScrollBars = ScrollBars.None;
// continue to populate rows such as dbv.Rows.Add(obj);
dbv.ScrollBars = sc; // restore the scroll bar setting back

With above codes, the scroll bar reappears fine after data refresh. The problem is that the application requires to set certain cell as selected after the refresh:

dbv.CurrentCell = dbv[0, selectedRowIndex];

With above code, the cell is selected; however, the scroll bar's position does not reflect the position of the selected cell's row position. When I try to move the scroll bar after the refresh, the grid will jump to the first row.

It seems that the scroll bar position is set back to 0 after the reset. The code to set grid's CurrentCell does not cause the scroll bar to reposition to the correct place. There is no property or method to get or set scroll bar's value in DataGriadView, as far as I know.

I also tried to set the selected row to the top:

dbv.CurrentCell = dbv[0, selectedRowIndex];
dbv.FirstDisplayedScrollingRowIndex = selectedRowIndex;

The row will be set to the top, but the scroll bar's position is still out of sync. Not sure if there is any way to make scroll bar's position in sync with the selected row which is set in code?

© Stack Overflow or respective owner

Related posts about visual-studio-2005

Related posts about datagridview