Ho realizzato un form nel quale è possibile gestire il drag & drop tra due controlli listview, usando il codice disponibile a questa pagina http://msdn.microsoft.com/en-us/library/aa289508(VS.71).aspx nel capitolo "Dragging Between Lists" e che riporto poco sotto.
Come avrete notato le varie subroutine gestiscono più eventi contemporaneamente e questo permette di non duplicare il codice due volte (senza il doppio Handles infatti andrebbero realizzata una routine per gestire il drag & drop dal controllo 1 al controllo 2 e una routine per gestire il drag & drop dal controllo 2 al controllo 1). Nasce però un problema: in questo modo è anche possibile "l'auto drag&drop", in pratica è permesso trascinare un elemento di una lista, sulla lista stessa, duplicandolo. Siccome non voglio questo effetto indesiderato, come posso elmininare il problema senza duplicare il codice? Esiste un modo per identificare il controllo dal quale è partito il drag&drop in modo che con un controllo IF possa non eseguirlo se il controllo origine e destinazione sono uguali?
Grazie
codice:
Private Sub ListView_ItemDrag(ByVal sender As Object, ByVal e As _
System.Windows.Forms.ItemDragEventArgs) Handles ListView1.ItemDrag, _
ListView2.ItemDrag
Dim myItem As ListViewItem
Dim myItems(sender.SelectedItems.Count - 1) As ListViewItem
Dim i As Integer = 0
' Loop though the SelectedItems collection for the source.
For Each myItem In sender.SelectedItems
' Add the ListViewItem to the array of ListViewItems.
myItems(i) = myItem
i = i + 1
Next
' Create a DataObject containg the array of ListViewItems.
sender.DoDragDrop(New _
DataObject("System.Windows.Forms.ListViewItem()", myItems), _
DragDropEffects.Move)
End Sub
Private Sub ListView_DragEnter(ByVal sender As Object, ByVal e As _
System.Windows.Forms.DragEventArgs) Handles ListView1.DragEnter, _
ListView2.DragEnter
' Check for the custom DataFormat ListViewItem array.
If e.Data.GetDataPresent("System.Windows.Forms.ListViewItem()") Then
e.Effect = DragDropEffects.Move
Else
e.Effect = DragDropEffects.None
End If
End Sub
Private Sub ListView_DragDrop(ByVal sender As Object, ByVal e As _
System.Windows.Forms.DragEventArgs) Handles ListView1.DragDrop, _
ListView2.DragDrop
Dim myItem As ListViewItem
Dim myItems() As ListViewItem = _ e.Data.GetData("System.Windows.Forms.ListViewItem()")
Dim i As Integer = 0
For Each myItem In myItems
' Add the item to the target list.
sender.Items.Add(myItems(i).Text)
' Remove the item from the source list.
If sender Is ListView1 Then
ListView2.Items.Remove(ListView2.SelectedItems.Item(0))
Else
ListView1.Items.Remove(ListView1.SelectedItems.Item(0))
End If
i = i + 1
Next
End Sub