1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
|
Public Class Form1
Private persons As New List(Of Person)
Private rnd As New Random
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
DataGridView1.AllowDrop = True
For index = 1 To 10
Dim p As New Person() With {.Nom = "item" + index.ToString, .Salaire = rnd.NextDouble() * 100}
persons.Add(p)
Next
DataGridView1.DataSource = persons
End Sub
Private dragBoxFromMouseDown As Rectangle
Private rowIndexFromMouseDown As Integer
Private rowIndexOfItemUnderMouseToDrop As Integer
Private Sub DataGridView1_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles DataGridView1.MouseDown
rowIndexFromMouseDown = DataGridView1.HitTest(e.X, e.Y).RowIndex
If (rowIndexFromMouseDown <> -1) Then
Dim dragSize As Size = SystemInformation.DragSize
dragBoxFromMouseDown = New Rectangle(New Point(e.X - (dragSize.Width / 2),
e.Y - (dragSize.Height / 2)),
dragSize)
Else
dragBoxFromMouseDown = Rectangle.Empty
End If
End Sub
Private Sub DataGridView1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles DataGridView1.MouseMove
If e.Button And MouseButtons.Left = MouseButtons.Left Then
If dragBoxFromMouseDown <> Rectangle.Empty And
Not dragBoxFromMouseDown.Contains(e.X, e.Y) Then
Dim dropEffect As DragDropEffects = DataGridView1.DoDragDrop(
DataGridView1.Rows(rowIndexFromMouseDown), DragDropEffects.Move)
End If
End If
End Sub
Private Sub DataGridView1_DragOver(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles DataGridView1.DragOver
e.Effect = DragDropEffects.Move
End Sub
Private Sub DataGridView1_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles DataGridView1.DragDrop
Dim clientPoint As Point = DataGridView1.PointToClient(New Point(e.X, e.Y))
rowIndexOfItemUnderMouseToDrop =
DataGridView1.HitTest(clientPoint.X, clientPoint.Y).RowIndex
If (e.Effect = DragDropEffects.Move) Then
Dim rowToMove As DataGridViewRow = CType(e.Data.GetData(GetType(DataGridViewRow)), DataGridViewRow)
Dim p As Person = CType(rowToMove.DataBoundItem(), Person)
persons.RemoveAt(rowIndexFromMouseDown)
persons.Insert(rowIndexOfItemUnderMouseToDrop, p)
'refresh
DataGridView1.Invalidate()
End If
End Sub
End Class |
Partager