2

i try to add the option to my application to drag file into my Listbox instead of navigate into the file folder and this is what i have try:

private void Form1_Load(object sender, EventArgs e)
{
    listBoxFiles.AllowDrop = true;
    listBoxFiles.DragDrop += listBoxFiles_DragDrop;
    listBoxFiles.DragEnter += listBoxFiles_DragEnter;
}

private void listBoxFiles_DragEnter(object sender, DragEventArgs e)
{
    e.Effect = DragDropEffects.Copy;
}

private void listBoxFiles_DragDrop(object sender, DragEventArgs e)
{
    listBoxFiles.Items.Add(e.Data.ToString());
}

but instead of the full file path e.Data.ToString() return System.Windows.Forms.DataObject

user3271698
  • 145
  • 3
  • 9
  • 19

2 Answers2

10

This code I found here:

private void Form1_Load(object sender, EventArgs e)
{
    listBoxFiles.AllowDrop = true;
    listBoxFiles.DragDrop += listBoxFiles_DragDrop;
    listBoxFiles.DragEnter += listBoxFiles_DragEnter;
}

private void listBoxFiles_DragEnter(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy;
}

private void listBoxFiles_DragDrop(object sender, DragEventArgs e)
{
    string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
    foreach (string file in files)
        listBoxFiles.Items.Add(file);
}
Community
  • 1
  • 1
AsfK
  • 3,328
  • 4
  • 36
  • 73
1

I tried using @AsfK's answer in WPF, had to delete

listBoxFiles.DragDrop += listBoxFiles_DragDrop;

from public MainWindow() else I got the dragged files duplicated.

Thanks!

Yannis
  • 1,682
  • 7
  • 27
  • 45