How can the focus row of a DataGrid follow the data when a DataGrid column is sorted?

When a DataGrid column is sorted, we want the focus row to follow the data as it changes DataGrid rows.  For example. if order# 1234 is in DataGrid row 4 before the sort and lands in row 20 after a column is sort, we want row 20 to have the focus.
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

It's a bit of a fudge, but it works for me.  

Add a listbox to the same form as your datagrid and set its .Visible property to False.  Bind it to the same datasource as your datagrid and use as its .DisplayMember some column from the datagrid that has a unique value in each record.  Then add the following code (with appropriate names/values substituted)to your form

    Private lastvalue As Object

    Private Sub OnListChanged(ByVal sender As Object, ByVal args As System.ComponentModel.ListChangedEventArgs)
        Dim i As Integer = HiddenListBox.FindStringExact(CStr(lastvalue))
        HiddenListBox.SelectedIndex = i
    End Sub

    Private Sub dataGrid_CurrentCellChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles dataGrid.CurrentCellChanged
        lastvalue = dataGrid(dataGrid.CurrentRowIndex, 0)
    End Sub

and, at the end of the procedure in which you load your dataGrid

    AddHandler YourDataSet.Tables(YourTable).YourView.ListChanged, New System.ComponentModel.ListChangedEventHandler(AddressOf OnListChanged)

The CurrentCellChanged sub records the unique value from the last row selected before any sort.

The OnListChanged sub finds that value in the hidden listbox after the sort and selects it.  Because the datagrid is bound to the same datasource, the same row is selected in that.


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.