MSTR
MSTR

Reputation: 1

Scrollbar position after refreshing Datagridview vb.net

I am working on a system that will collect data from different computers.

My requirement is when I refresh the datagridview to view the input data in my database then the selected row should be selected and the scroll bar position should be at the same location, because when the refresh happens the scroll bar is moved to the top of the grid. Any help would be appreciated!

Im using this code to refresh the DataGridView

Private Sub Form_Load(sender As object, e As EventArgs) Handles MyBase.Load

RefreshData()
End Sub

Private Sub AutoRefresher_tick(sender As object, e As EventArgs) Handles AutoRefresher.Tick
DatagridView()
End Sub

Sub RefreshData()
Dim timer as new Timer
timer.Interval = 5000
addHandler timer.tick, Addressof AutoRefresher_Tick
timer.start()
End Sub

Upvotes: 0

Views: 314

Answers (1)

jmcilhinney
jmcilhinney

Reputation: 54417

"Selection" is a bad term here because "selection" means something specific in a DataGridView and it's not what you need. The SelectedRows property is a collection of rows that are selected, i.e. highlighted. What matters here is where the caret is located and that is the "current" row, not the "selected" row. The CurrentRow property is a single row and it is the row that contains the CurrentCell, which is the cell that contains the caret.

What you need to do is get the CurrentRow before the refresh, store a unique identifier for that record, do the refresh, find the new row that contains that identifier and make that the current row. Ideally, you should be binding data via a BindingSource and then you can use the Current and Position property of that, e.g.

Dim currentRecord = DirectCast(BindingSource1.Current, DataRowView)
Dim currentId = currentRecord("Id")

'Refresh data here.

Dim position = BindingSource1.Find("Id", currentId)

BindingSource1.Position = position

Upvotes: 1

Related Questions