Drag and Drop in Windows Forms - A Primer

The Listview Control

Into more useful territory yet again. The beloved Listview and Treeview controls are the most common controls you will see using D&D in applications. I've chosen the Listview because I managed to find an example of a TreeView on Microsoft's site and I decided to adapt it for the Listview which differs in only one way but which might cause problems. For reference the Treeview example can be found here.

So lets go straight to the code and I'll explain:-

Private Sub ListViewItemDrag(ByVal sender As Object, ByVal e As System.Windows.Forms.ItemDragEventArgs) Handles ListView1.ItemDrag, ListView2.ItemDrag
    DoDragDrop(e.Item, DragDropEffects.Move)
End Sub

Private Sub ListViewDragEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles ListView1.DragEnter, ListView2.DragEnter
    e.Effect = DragDropEffects.Move
End Sub

Private Sub ListViewDragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles ListView1.DragDrop, ListView2.DragDrop
    Dim lvItem As ListViewItem
     Dim destItem As ListViewItem
     Dim destLv As ListView = CType(sender, ListView)
     Dim clX As Integer = destLv.PointToClient(New Point(e.X, e.Y)).X
     Dim clY As Integer = destLv.PointToClient(New Point(e.X, e.Y)).Y
     If e.Data.GetDataPresent("System.Windows.Forms.ListViewItem", False) Then
         'dragging a listview item
         lvItem = CType(e.Data.GetData("System.Windows.Forms.ListViewItem"), ListViewItem)
         destItem = CType(sender, ListView).GetItemAt(clX, clY)
         destLv.Items.Insert(destItem.Index, lvItem.Clone)
     End If
End Sub

You might also like...


About the author

Brian O'Connell Ireland

Microsoft Certified Applications Developer with 10 years experience developing web based applications using asp, asp.net for a Local Authority in Dublin. Clings to a firm belief that a web appli...

Interested in writing for us? Find out more.


Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Engineers are all basically high-functioning autistics who have no idea how normal people do stuff.” - Cory Doctorow