DataGridView Selected Row Move UP and DOWN

后端 未结 13 1494
盖世英雄少女心
盖世英雄少女心 2020-12-06 01:31

How can I allow selected rows in a DataGridView (DGV) to be moved up or down. I have done this before with a ListView. Unfortunetly, for me, replacing the DGV is not an opt

13条回答
  •  天命终不由人
    2020-12-06 02:09

    data bound solution with multi-selection support, use SharpDevelop 4.4 to convert to C#.

    
    Sub MoveSelectionUp(dgv As DataGridView)
        If dgv.CurrentCell Is Nothing Then Exit Sub
        dgv.CurrentCell.OwningRow.Selected = True
        Dim items = DirectCast(dgv.DataSource, BindingSource).List
        Dim selectedIndices = dgv.SelectedRows.Cast(Of DataGridViewRow).Select(Function(row) row.Index).Sort
        Dim indexAbove = selectedIndices(0) - 1
        If indexAbove = -1 Then Exit Sub
        Dim itemAbove = items(indexAbove)
        items.RemoveAt(indexAbove)
        Dim indexLastItem = selectedIndices(selectedIndices.Count - 1)
    
        If indexLastItem = items.Count Then
            items.Add(itemAbove)
        Else
            items.Insert(indexLastItem + 1, itemAbove)
        End If
    End Sub
    
    
    Sub MoveSelectionDown(dgv As DataGridView)
        If dgv.CurrentCell Is Nothing Then Exit Sub
        dgv.CurrentCell.OwningRow.Selected = True
        Dim items = DirectCast(dgv.DataSource, BindingSource).List
        Dim selectedIndices = dgv.SelectedRows.Cast(Of DataGridViewRow).Select(Function(row) row.Index).Sort
        Dim indexBelow = selectedIndices(selectedIndices.Count - 1) + 1
        If indexBelow >= items.Count Then Exit Sub
        Dim itemBelow = items(indexBelow)
        items.RemoveAt(indexBelow)
        Dim indexAbove = selectedIndices(0) - 1
        items.Insert(indexAbove + 1, itemBelow)
    End Sub
    

提交回复
热议问题