Goto Home Page

Programming the data grid view control in Visual Basic

In this short video I am going to show you how to maintain the current scroll position, when repopulating a data grid view control, especially when using a large data set.

Video transcript

Here, I have a fairly long list of database records, and let’s say the user has scrolled down the list and picked an entry for editing, typically you would re-populate the data grid, to reflect the changes the user has made. If you just do a simple re-fresh, then as you can see the scroll bar position goes back to the start of the grid, and the user loses the position they where at, which makes for a frustrating user experience.

However, if I use this button, the data grid is repopulated with all the new data, yet this time the software automatically scrolls to the position the user was at, keeping them happy.

So let’s take a look at the code behind this button.

The solution is quite easy really, I define an integer variable called first displayed row, and before I call my populate grid routine, I store the value of the first displayed row index into this variable. I then call my populate grid routine, which connects to my database and retrieves all the data displaying it in the grid control. Finally I restore the value of the scrolling row index, back it’s last known position. It’s that simple.

I hope you found this tip useful, I’ll include the source code below, so you can just cut and paste it into your own projects.

VB source code

Dim intFirstDisplayedRow As Integer

Me.Cursor = Cursors.WaitCursor
MySQL.Connect()

' Store the value of the first displayed row index
intFirstDisplayedRow = GridResults.FirstDisplayedScrollingRowIndex

PopulateGrid()

' Restore the scroll position back to the saved position
GridResults.FirstDisplayedScrollingRowIndex = intFirstDisplayedRow

MySQL.Disconnect()
Me.Cursor = Cursors.Arrow

About the author

Paul Bradley is a full time software developer, specialising in creating medical software for the national health service. He has been writing computer code since early 1990 and has developed web sites since April 2000.

This article was first published on 30.11.2010


© copyright 2004–2012
HomeContactColophonDisclaimer