Reader Level:
ARTICLE

Drag and Drop using C#

Posted by Chris Blake Articles | Windows Forms C# November 13, 2002
To allow your program to accept files using the drag and drop, you must first pick a control that you wish to be able to accept them.
  • 0
  • 0
  • 50230

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 );
}
}

Article Extensions
Contents added by sindhu patro on Jun 18, 2009
Download File: ImpactPms_100609.zip
COMMENT USING

Trending up