How To Do Drag And Drop

Drag and Drop is a very basic C# / windowing function. It may seem daunting, but its actually easy to do. This example shows you how to drag and drop a file that contains an image into a pictureBox, and some text. It is limited in that it does not resize the image to fit into the pictureBox, but you can do this yourself.

Download: DragAndDropExample.zip - Demonstrates dragging an dropping.
Unzip all files (executables plus dependencies) into a single folder.

Create a form with a pictureBox (called pictureBox1) docked to fill, and a label (called label1) docked to the bottom.

Set the Properties. In the Form's Properties pane, set the

  • AllowDrop Property of the Form to True
  • Text Property of label1 to "Drag and drop image files and text"

Create event handlers (click the lightning bolt in the Properties pane) for:

  • DragDrop : Form1_DragDrop
  • DragOver : Form1_DragOver

For these two event handlers insert the following code

// Decide if this form can accept the target, and if so give feedback that it can
private void Form1_DragOver(object sender, System.Windows.Forms.DragEventArgs e)
{
  // Check to see if the drag event contains a file data type,
  // i.e., that we are dragging a file. Ignore all other drages.
  if ( e.Data.GetDataPresent(DataFormats.FileDrop) ||
      e.Data.GetDataPresent(DataFormats.Text) )
  {
    // Change the feedback (the effect) to show that this drag is allowable
    if ((e.AllowedEffect & DragDropEffects.Move) != 0)
      e.Effect = DragDropEffects.Move;
  } 
}

// When a file (and only a file) is dropped onto this form, check if its in
// image and put it into the pictureBox
private void Form1_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
{
  try
  { 
    // If we drop a file try and load it into the image box
    if (e.Data.GetDataPresent (DataFormats.FileDrop))
    {
      // Get the file path of the file and load it
      string[] filepath = (string[]) e.Data.GetData (DataFormats.FileDrop);
      Image image = Image.FromFile (filepath[0]);
      pictureBox1.Image = image;
    }
    // If we drop a string, try and load it to the label
    if (e.Data.GetDataPresent (DataFormats.StringFormat) )
    {
      label1.Text = (string) e.Data.GetData (DataFormats.StringFormat);
    }
  } catch (Exception exc) {}

}

Compile and Test

  • drag an image file over the form. Note how the cursor changes to accept it, and how the drop copies the image into the picture box.
  • do the same with text, and notice how it is inserted in the label