Adding Drag & Drop to a Windows Forms TextBox to get a file path

As first thing we have to set the AllowDrop property of the TextBox to True from the designer.

After this we have to handle 2 events to manage when a file is dropped into the TextBox in order to print its path. These events are:

  • DragEnter: defines what to do against any attempt to drop something into the TextBox, based on which kind of item we are trying to drop. With this event we can allow only some kind of item to be dropped to our control. For our purpose we have to specify that we are interested just in file drops.
  • DragDrop: defines what to do when an allowed item is dropped to our control. In our case we want to extract the file path and to print in in the TextBox itself.
private void textXml_DragEnter(object sender, DragEventArgs e)
{
    e.Effect = e.Data.GetDataPresent(DataFormats.FileDrop)
        ? DragDropEffects.Link
        : DragDropEffects.None;
}

private void textXml_DragDrop(object sender, DragEventArgs e)
{
    ((TextBox)sender).Text =
        ((string[])e.Data.GetData(DataFormats.FileDrop, false)).First();
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s