listview drag drop handling [resolved]
I'm wondering if anyone's got any working samples of dragging and dropping items and subitems to and from listviews. What I'm trying to do specifically is drag an item from a listbox to a listview 's item text.
I would think this would be easy to do with the GetItemAt method, but I can't get it to work. Any help would be appreciated.
Sibby
After a day of on and off putzing....
I finally got this working how I want it. To get a sample of this working for yourself, add a listview and listbox control to your form.
In my case I wasn't worried about dropping into a specific subitem, but this should give anyone else a start to getting that functionality working as well.
VB Code:
Dim iSelectedIndex As Integer
Dim iLastItemIndex As Integer
Private Sub Listview1_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles Listview1.DragDrop
'get the text from our dropped item and assign it to the hovered item's text property
Dim sData As String = e.Data.GetData(DataFormats.Text).ToString()
Listview1.Items(iLastItemIndex).Text = sData
End Sub
Private Sub Listbox1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Listbox1.MouseMove
'if holding down left mouse, start our dragdrop by passing the selected index from the listbox
If e.Button = MouseButtons.Left Then
Listbox1.DoDragDrop(Listbox1.Items(iSelectedIndex), DragDropEffects.Copy)
End If
End Sub
Private Sub Listview1_DragEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles Listview1.DragEnter
'set the drag effect based on our drag data
If e.Data.GetDataPresent(DataFormats.Text) Then
e.Effect = DragDropEffects.Copy
Else
e.Effect = DragDropEffects.None
End If
End Sub
Private Sub Listbox1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Listbox1.MouseDown
'save off the current selection because it doesn't get set in the mousemove or click event
iSelectedIndex = Listbox1.SelectedIndex
End Sub
Private Sub Listview1_DragOver(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles Listview1.DragOver
'find the currently hovered item, select it and save it off
Dim cp As Point = Listview1.PointToClient(New Point(e.X, e.Y))
Dim hoverItem As ListViewItem = Listview1.GetItemAt(cp.X, cp.Y)
If Not (hoverItem Is Nothing) Then
e.Effect = DragDropEffects.Copy
iLastItemIndex = hoverItem.Index
Listview1.Items(iLastItemIndex).Selected = True
Else
e.Effect = DragDropEffects.None
End If
End Sub
Sibby