Drag and Drop using C#

I was working on an App and needed Drag & Drop support for it. I thought it’ll be complicated but its very easy. Here’s how its done:

For this tutorial I’ll be using a listBox. You can use any control but make sure you set the “AllowDrop” to “true“.

Checking what has been dragged

Select the listBox and add the DragEnter event.

Add this code:

private void listBox1_DragEnter(object sender, System.Windows.Forms.DragEventArgs e)
 {

 // This will make sure that a file has been dropped and not text,folders or something else

 if (e.Data.GetDataPresent(DataFormats.FileDrop, false))

 {

 // This will allow the files to be dragged into the control

 e.Effect = DragDropEffects.All;

 }

 }

The above code first makes sure that files are dragged and not text, folders etc; and then allows the files to be dragged into the control.

Handling the drop

Select the listBox and add the DragDrop event.

Add this code:

  private void listBox1_DragDrop(object sender,System.Windows.Forms.DragEventArgs e)

    // Save the filenames of the dragged files into a string[] array

    string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);

    foreach (string fileNames in files )

    {

    // Add all the file names to the listBox

    listBox1.Items.Add( fileNames );

    }

    }

And that’s it.

If you want to do something different with the drag/drop files instead of only adding it to the listBox, don’t hesitate to post a comment.

9 thoughts on “Drag and Drop using C#

  1. I would appreciate more visual materials, to make your blog more attractive, but your writing style really compensates it. But there is always place for improvement

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>