Drag and drop operation between two Listbox using vb.net

 
The following example demonstrates how to perform a drag and drop operation between two listbox controls in vb.net

Example

this example requires one windows form that contains Two listbox controls named ListBox1 and ListBox2, Use the toolbox to add two listbox controls to Form1. Change the AllowDrop property of both ListBox1 and ListBox2 to True in the Properties window.

Generate method handler for Load event of Form1 and use this code for binding items to ListBox1 :

Private Sub Form1_Load(ByVal sender As System.Object, _
                           ByVal e As System.EventArgs) Handles MyBase.Load
        ListBox1.Items.Add("NewDelhi")
        ListBox1.Items.Add("Kolkata")
        ListBox1.Items.Add("Londan")
        ListBox1.Items.Add("Sydney")
        ListBox1.Items.Add("NewYork")
        ListBox1.Items.Add("Dubai")
End Sub

Generate method handler for MouseDown event of ListBox1 and use this code :

    Private Sub ListBox1_MouseDown(ByVal sender As System.Object, _
                     ByVal e As System.Windows.Forms.MouseEventArgs) Handles ListBox1.MouseDown
        If ListBox1.Items.Count = 0 Then
            Return
        End If
        Dim index As Integer = ListBox1.IndexFromPoint(e.X, e.Y)
        Dim sourceStr As String = ListBox1.Items(index).ToString()
        Dim objDragDropEff As DragDropEffects = DoDragDrop(sourceStr, DragDropEffects.All)
        If objDragDropEff = DragDropEffects.All Then
            ListBox1.Items.RemoveAt(ListBox1.IndexFromPoint(e.X, e.Y))
        End If
    End Sub

Generate method handler for DragEnter event of ListBox2 and use this code :

    Private Sub ListBox2_DragEnter(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles ListBox2.DragEnter
        e.Effect = DragDropEffects.All
    End Sub

Generate method handler for DragDrop event of ListBox2 and use this code :

    Private Sub ListBox2_DragDrop(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles ListBox2.DragDrop
        Dim str As String = CStr(e.Data.GetData(DataFormats.StringFormat))
        ListBox2.Items.Add(str)
    End Sub