Drag and Drop using C#

To allow your program to accept files using drag and drop, you must first pick a control that you wish to be able to accept them. This can be for example a Form, a ListBox or a TextBox

There are really two steps to this process:

  1. You must have your control check what is being dragged over itself - and state whether or not it can accept it.

  2. You must handle what is actually dropped.

Part 1 - Checking what the user is trying to drop:

Select your control (in this example im going to use a ListBox that will display all the paths of all the files dropped onto it), once selected change the property AllowDrop to true. Now you must add the event DragEnter.

Now place in the following code:

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

Part 2 -  Handling the dropped files:

Now you need to add the DragDrop event, and place in the following code. (You obviously may want to do something different with your file than simply place its path into a ListBox)

private void listBox1_DragDrop(object sender,System.Windows.Forms.DragEventArgs e)
foreach (string fileName in (string[])e.Data.GetData(DataFormats.FileDrop) )
listBox1.Items.Add( fileName );

Similar Articles