views:

230

answers:

1

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?

A: 

I found an answer to resolve issue. As I mentioned that the control does not have methods or properties to set the correct scroll bar value. However, the scroll bar and the DatagridView content will display correct if there is an interaction directly towards to the UI such as touch the scroll bar or grid cell. It looks like that the control needs to be refocused and a repaint.

Simply use the following codes does not cause the scroll bar reset:

 dgv.Select();
 // or dbv.Focuse();

The way I found is that I have to make the DatagridView control disappear to back again. Fortunately, I have a tab control with several tabs. Then I switch the tab to get scroll bar reset:

int index = myTabCtrl.SelectedIndex;
if (index == (myTabCtrl.TabCount)) {
  dgv.SeletecedIndex = 0;
}
else {
  dgv.SelectedIndex = index + 1;
}
myTabCtrl.SelectedIndex = index;

If you don't have any way to hide the DatagridView on your form, you could simply minimize the form and then restore it back.

The problem is that there will be a fresh on the UI.

David.Chu.ca