Tutorial :Remember selected row in DataGridView


I'm trying to get my datagridview control to remember the selected row after data refresh.
The DGV is databound to a list of business objects:

Dim FXs As SortableBindingList(Of FX) = FX.LoadAllForBinding(FXStatus)   Dim bs As New BindingSource  bs.DataSource = FXs  

The overall sequence is something like this:

  1. User clicks on a row
  2. Row index is saved in a variable
  3. User edits data in pop up form and closes when finished
  4. Datagridview is refreshed (re-bound from scratch)
  5. Selected row is set to the previously saved index (in DataBindingComplete event of DGV)

    Me.dgvMain.Rows(_CurrentSelectedRowNo).Selected = True

This seems to work fine, the selected row is set correctly (at least the count goes from 0 to 1). However what happens next is that the debugger jumps into the properties of the bound business object (presumably reading them for binding), so that DataBindingComplete event seems to fire BEFORE the DataBinding has been done.

The DGV can have up to about 300 rows so it's pretty annoying for the user that it jumps back to row zero each time they edit a row!

Am I doing something obviously wrong here? Should I be using a different event for this?


I'm doing something similar, but not using a grid event to determine when to refresh. I call my refresh routine after they're done editing in the edit form.

The problem with using the grid row number is it could have changed after or during the edit, especially if you're supporting multiple users and your grid is a view of a table on a server, or if they can sort the grid rows.

I have to use the row's PK value(s) to identify the changed row, and considering they could change one of the pk values during the edit, I need to keep track of the updated PK value as well.

I raise my own event when they update a value.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »