Drag and Drop


The Source control is where you are copying/moving from and the Target is where you are moving to.


DoDragDrop Method

Dragging is initiated by calling the DoDragDrop method for the Source control
This takes two parameters
data - specifying the data to pass
aalowdEffects - specifying which operations (copying and/or moving) are allowed
A new DataObject is automatically created


GiveFeedback Event

This in turn raises the GiveFeedback event.
This allows you to display a custom mouse pointer.


AllowDrop Property

Any control which has its AllowDrop property set to True is a potential drop target.


DragEnter Event

As the mouse passes over a control the DragEnter event is raised
The GetDataPresent method is used to make sure that the format of the data is appropriate to the target control and the Effect property is used to display the appropriate mouse pointer.


DragDrop Event

If the user releases the mouse button over the target the DragDrop event is raised
Code in the DragDrop event handler extracts the data from the DataObject and displays it in the target control.



Dragging Files

In this example drag and drop is used to populate a ListBox control with a list of files dragged from Windows Explorer.


To enable drag and drop for a file


Add a ListBox control to a form and set its AllowDrop property to True.

Private Sub ListBox1_DragEnter(ByVal sender As Object, _ 
                               ByVal e As System.Windows.Forms.DragEventArgs) _
                               Handles ListBox1.DragEnter

    If e.Data.GetDataPresent(DataFormats.FileDrop) Then
        e.Effect = DragDropEffects.All
    End If
End Sub

You may notice that the Effect is set to DragDropEffects.All. Because the files themselves are not actually being moved or copied, it does not really matter which AllowedEffects were set by the source, so specifying All means that dropping is enabled for


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

    If e.Data.GetDataPresent(DataFormats.FileDrop) Then
        Dim MyFiles() As String
        Dim i As Integer

' Assign the files to an array.
        MyFiles = e.Data.GetData(DataFormats.FileDrop)
' Loop through the array and add the files to the list.
        For i = 0 To MyFiles.Length - 1
            ListBox1.Items.Add(MyFiles(i))
        Next
    End If
End Sub

The FileDrop format contains the full path for each file being dropped. Rather than populating a list, you could just as easily perform other operations on the files for example, opening them in MDI (multiple-document interface) document windows.


The next example demonstrates a special case for drag and drop: dragging items back and forth between two lists.




© 2017 Better Solutions Limited. All Rights Reserved. © 2017 Better Solutions Limited

PrevNext