Click here to Skip to main content
15,032,024 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to figure out how to use the drag and drop event to switch the order of the listbox items. every time I try to use my code it keeps giving me a circle with a line through it. no matter what I do I cant get them to move.

Private Sub ListBox1_MouseDown(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles ListBox1.MouseDown

       Dim index As Integer = ListBox1.IndexFromPoint(e.X, e.Y)
       Dim s As String = ListBox1.Items(index).ToString()
       Dim dde1 As DragDropEffects = DoDragDrop(s, DragDropEffects.Move)

       If dde1 = DragDropEffects.All Then
           ListBox1.Items.RemoveAt(ListBox1.IndexFromPoint(e.X, e.Y))
       End If

   End Sub
   Private Sub ListBox1_DragOver(sender As Object, e As System.Windows.Forms.DragEventArgs) Handles ListBox1.DragEnter

       e.Effect = DragDropEffects.All
   End Sub

   Private Sub ListBox1_DragDrop(sender As Object, e As System.Windows.Forms.DragEventArgs) Handles ListBox1.DragDrop

       If e.Data.GetDataPresent(DataFormats.Text) Then
           e.Effect = DragDropEffects.Move
           ListBox1.SelectedIndex = ListBox1.IndexFromPoint(ListBox1.PointToClient(New Point(e.X, e.Y)))
       End If
       Dim str As String = DirectCast(e.Data.GetData(DataFormats.StringFormat), String)
       ListBox1.Items.Insert(ListBox1.SelectedIndex, str)

   End Sub

What I have tried:

changed .move to .copy but I still get the same circle with the line through it.
Updated 17-Jan-17 9:23am
Michael_Davies 17-Jan-17 1:46am
Have you set the property AllowDrop to True on the listbox?
Member 11856456 17-Jan-17 1:54am
yeah, it was suggested that my code is wrong because now it's allowing me to drag and drop, but nothing happens. I want to rearrange the list box so that I have certain items in a new position/index
Member 11856456 17-Jan-17 15:13pm
I have made it further, problem is once its place in the appropriate index it copies the same text making a duplicate, but removes the other text. I am reposting the new code.

1 solution

I'd suggest to read this: Implementing Drag and Drop in Visual Basic .NET[^]

As to your code...
Inside ListBox1_DragDrop procedure you have to add this line:
Dim myitem = DataFormats.Text

Above code enable you to copy item. Now, you have to provide code to remove item, which have ben moved.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900