Recipe 14.14. Dragging and Dropping Files to a ListBox


You want a ListBox control to accept file paths dragged to it from Windows Explorer.


Sample code folder: Chapter 14\DragDropFiles

Use the control's DragEnter and DragDrop events to watch for dropped file lists and process them when dropped.


Create a new Windows Forms application, and add a ListBox control named ListBox1 to Form1. Set this control's AllowDrop property to TRue. Now add the following code to the form's source code:

 Private Sub ListBox1_DragEnter(ByVal sender As Object, _       ByVal e As System.Windows.Forms.DragEventArgs) _       Handles ListBox1.DragEnter    ' ----- Allow the dropping of file lists.    If (e.Data.GetDataPresent(DataFormats.FileDrop) = _          True) Then       e.Effect = DragDropEffects.Copy    End If End Sub Private Sub ListBox1_DragDrop(ByVal sender As Object, _       ByVal e As System.Windows.Forms.DragEventArgs) _       Handles ListBox1.DragDrop    ' ----- Process each dropped file.    For Each oneFile As String In _          e.Data.GetData(DataFormats.FileDrop)       ListBox1.Items.Add(oneFile)    Next oneFile End Sub 

To test the program, run it, and then drag one or more files from Windows Explorer (or any other program that supports the dragging of files). Figure 14-12 shows the result of a multifile drag operation.

Accepting dragged files in a control is a two-step process:

  1. Inform the sender of your acceptance criteria through the DragEnter event handler.

  2. Accept the files through the DragDrop event handler.

In this recipe's code, the DragEnter event examines the data being dragged into the ListBox to determine if it will accept the content. In this case, it looks for a "file drop list" (identified by DataFormats.FileDrop). If it finds one, it tells the sender that it will accept the files through a Copy operation, setting the e.Effect property. By default, e.Effect is set to DragDropEffects.None, which indicates that the content is not acceptable.

Figure 14-12. Three dragged files accepted by a ListBox control

In the DragDrop event, the dragged content exposed through e.Data is accessed, and its "file drop list" content is extracted as a string array, which is then transferred to the ListBox control.

If you are familiar with the clipboard operations exposed through the My.Computer.Clipboard object, you will recognize the use of the "file drop list" also available through the clipboard.

See Also

Recipe 14.15 shows you how to perform inter-ListBox drag-and-drop operations.

Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: