Home > Mobile >  How to drag and drop one file at the time?
How to drag and drop one file at the time?

Time:09-17

I have a WinForms application where I allow users to drag and drop images onto a panel. For now, they need to drop two files at once to add them both. If they drop one and then they want to add another, it just overwrites the first file.

I want to allow them to drop one file at once, and add as many as they want without overwriting them.

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

string[] files;
private void Panel1_DragDrop(object sender, DragEventArgs e)
{
   files = (string[])e.Data.GetData(DataFormats.FileDrop);
   foreach (string file in files)
   {
      Console.WriteLine(files.Length);
   }
}

CodePudding user response:

The reason it doesn't work is that you're throwing away whatever is in files every time DragDrop is raised. Instead of using an array, you should use List<string> (or HashSet<string> to ignore duplicates).

Here's an example:

List<string> files = new List<string>();
private void Panel1_DragDrop(object sender, DragEventArgs e)
{
    files.AddRange((string[])e.Data.GetData(DataFormats.FileDrop));
    Console.WriteLine(files.Count);
}

Or with HashSet:

HashSet<string> files = new HashSet<string>();
private void Panel1_DragDrop(object sender, DragEventArgs e)
{
    files.UnionWith((string[])e.Data.GetData(DataFormats.FileDrop));
    Console.WriteLine(files.Count);
}
  • Related