这段代码
CurrentSelectedRow = Me.dgvPreviouslyCut.CurrentRow.Index
存储用户在数据网格视图控件中单击的当前选定行。 刷新数据网格视图的数据源后,这段代码
Me.dgvPreviouslyCut.Rows(CurrentSelectedRow).Selected = True
以编程方式重新选择同一行。
紧接着
Me.dgvPreviouslyCut.CurrentRow.Index
始终设置为零,而不是您期望的变量 CurrentSelectedRow。
为什么以编程方式设置选择行索引不会导致属性 CurrentRow.Index 设置为相同的值?
CurrentRow
是包含当前活动单元格的行。当您将 DataGridView 绑定到外部数据源时,此属性将重置为其默认值,即第一列中的第一个单元格。
SelectedRow
是当前选择/突出显示的行。它可能是一行或多行,具体取决于 MultiSelect
属性。要选择一行,您必须将其 Selected
属性设置为 true。
通过将行设置为选定的,您只是将其突出显示,而不是使其处于活动状态。
要保留当前单元格,您必须存储当前单元格的行索引和列索引。要获取它们,请使用
CurrentCellAddress
属性。刷新后 DataSource
使用这些索引设置 CurrentCell 属性。
dataGridView1.CurrentCell = dataGridView1.Rows(rowindex).Cells(columnindex);
当数据源更改时,
DataGridView
会创建一个新的CurrencyManager。如果此 CM 包含项目,则默认位置为 0
,因此将其推送到 DGV 并选择第一行。
要解决此问题,只需设置 CM 的位置即可:
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
一个简单的技巧是获取当前行索引:
int RowNumber = YourDataGridView.CurrentRow.Index;
刷新数据源/datagridview后,您可以使用以下方法重新选择上一行索引:
YourDataGridView.ClearSelection();
YourDataGridView.CurrentCell = YourDataGridView.Rows[RowNumber].Cells[0];
这应该重新选择具有正确索引的先前选择的行。