Question

This code

CurrentSelectedRow = Me.dgvPreviouslyCut.CurrentRow.Index

stores the current selected row that has been clicked by the user in a data grid view control . After refreshing the datasource for the data grid view, this code

Me.dgvPreviouslyCut.Rows(CurrentSelectedRow).Selected = True

programmatically re-selects the same row.

Immediately afterwards though

 Me.dgvPreviouslyCut.CurrentRow.Index

is always set to zero, NOT the variable CurrentSelectedRow as you would expect.

Why does programmatically setting the select row index not cause the property CurrentRow.Index to be set to the same?

Was it helpful?

Solution

CurrentRow is the row containing the currently active cell. When you bind the DataGridView to an external data source, this property is reset to its default value which is the first cell in the first column.

SelectedRow is the row which is currently selected/highlighted. It may be one or more rows depending on MultiSelect property. To select a row you have to set its Selected property to true.

By setting the row as selected you merely keeping it highlighted not making it active.

To retain the current cell you have to store the Current cell's row and column index. To get them use the CurrentCellAddress property. Once your refresh the DataSource set the CurrentCell property using these indexes.

dataGridView1.CurrentCell = dataGridView1.Rows(rowindex).Cells(columnindex);

OTHER TIPS

The DataGridView creates a new CurrencyManager when the data source is changed. If this CM contains items, the default position is 0, thus pushing this to the DGV and selects the first row.

To fix this, just set the position of the CM instead:

Me.dgvPreviouslyCut.DataSource = my_new_datasource

Dim cm As CurrencyManager = CType(Me.BindingContext(my_new_datasource), CurrencyManager)

If ((Me.CurrentSelectedRow > -1) AndAlso (Me.CurrentSelectedRow < cm.Count)) Then
    cm.Position = Me.CurrentSelectedRow
End If
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top