Serialcoder en Français Serialcoder in English
TEL : +33 (0)9 72 13 15 17

Windows Forms FAQ resources

20. Windows Forms ListBox

20.3 How can I drag file names from Windows Explorer and drop them into a listbox?


Place a ListBox on your form, set its AllowDrop property and handle both DragEnter and DragDrop as below.

     private void listBox1_DragEnter(object sender, System.Windows.Forms.DragEventArgs e)
     {
          if (e.Data.GetDataPresent(DataFormats.FileDrop))
               e.Effect = DragDropEffects.All;
          else
               e.Effect = DragDropEffects.None;
     }

     private void listBox1_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
     {
          string[] files = (string[])e.Data.GetData("FileDrop", false);
          foreach (string s in files)
          {
               //just filename
               listBox1.Items.Add(s.Substring(1 + s.LastIndexOf(@"\")));

               //or fullpathname
               //     listBox1.Items.Add(s);
          }
     }

Here are some VB snippets.

     Private Sub listBox1_DragEnter(sender As Object, e As System.Windows.Forms.DragEventArgs)

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

     End Sub 'listBox1_DragEnter


     Private Sub listBox1_DragDrop(sender As Object, e As System.Windows.Forms.DragEventArgs)
          
          Dim files As String() = CType(e.Data.GetData("FileDrop", False), String())
          Dim s As String
          For Each s In files
               'just filename
               listBox1.Items.Add(s.Substring(1 + s.LastIndexOf("\")))

               or fullpathname
               ' listBox1.Items.Add(s)
          Next s

     End Sub 'listBox1_DragDrop