VB - Drag and Drop within grid (Reorder Rows)

Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Load
'Populate the grid.
Me.DataGridView1.Rows.Add("Jan", "1")
Me.DataGridView1.Rows.Add("Feb", "2")
Me.DataGridView1.Rows.Add("Mar", "3")
Me.DataGridView1.Rows.Add("Apr", "4")
End Sub
Private Sub DataGridView1_MouseDown(ByVal sender As Object,
ByVal e As System.Windows.Forms.MouseEventArgs) Handles DataGridView1.MouseDown
Dim hti = Me.DataGridView1.HitTest(e.X, e.Y)
If hti.Type = DataGridViewHitTestType.RowHeader Then
Me.DataGridView1.DoDragDrop(Me.DataGridView1.Rows(hti.RowIndex), DragDropEffects.Move)
End If
End Sub
Private Sub DataGridView1_DragEnter(ByVal sender As Object,
ByVal e As System.Windows.Forms.DragEventArgs) Handles DataGridView1.DragEnter
If Me.CanDrop(sender, e) Then
e.Effect = DragDropEffects.Move
End If
End Sub
Private Sub DataGridView1_DragOver(ByVal sender As Object,
ByVal e As System.Windows.Forms.DragEventArgs) Handles DataGridView1.DragOver
If Me.CanDrop(sender, e) Then
e.Effect = DragDropEffects.Move
End If
End Sub
Private Sub DataGridView1_DragDrop(ByVal sender As Object,
ByVal e As System.Windows.Forms.DragEventArgs) Handles DataGridView1.DragDrop
If Me.CanDrop(sender, e) Then
Dim rowToMove = DirectCast(e.Data.GetData(GetType(DataGridViewRow)), DataGridViewRow)
Dim location = Me.DataGridView1.PointToClient(New Point(e.X, e.Y))
Dim rowBounds As Rectangle
Dim rows = Me.DataGridView1.Rows
For rowIndex = Me.DataGridView1.RowCount - 1 To 0 Step -1
If Not rows(rowIndex).IsNewRow Then
rowBounds = Me.DataGridView1.GetRowDisplayRectangle(rowIndex, False)
If location.Y >= rowBounds.Y Then
If rowIndex <> rowToMove.Index Then
Dim newIndex = rowIndex
If rowToMove.Index <>
If location.Y > rowBounds.Y + rowBounds.Height \ 2 Then
newIndex += 1
End If
'Move the row to the new position.
rows.Remove(rowToMove)
rows.Insert(newIndex, rowToMove)
End If
Exit For
End If
End If
Next
End If
End Sub
Private Function CanDrop(ByVal sender As Object, ByVal e As DragEventArgs) As Boolean
Dim data = e.Data
Dim dataType = GetType(DataGridViewRow)
'Data can only be dropped if it is a row from the same DataGridView.
Return data.GetDataPresent(dataType) AndAlso _
DirectCast(data.GetData(dataType), DataGridViewRow).DataGridView Is sender
End Function
End Class

Comments