How to add DragDrop events on C#

If you are trying to figure out how to add DragDrop events in a c# control, coming an external file, then you've come to the right place.

DragDrop items are very useful, if you are trying to develop a tool that deals with external files. This can also be achieve with a FileBrowserDialog, but DragDrop items are more elegant IMO.

So, first you go to the c# control you wish to have this event. Go to the control property window and check if the control supports DragDrop and DragEnter events. In this case I'm using and extended ListView control.



We want to subscribe to the DragDrop, and DragEnter events. All you need to do is double click the events and it should generate proper codes you'll need later on.

DragEnter event, happens when a file is being drag into/over the control, here we want to simulate some effects by changing our mouse cursor (to achieve richer user experience).

      private void listView1_DragEnter(object sender, DragEventArgs e)
      {
          if (e.Data.GetDataPresent(DataFormats.Text))
          {
              e.Effect = DragDropEffects.Copy;
          }
          else if (e.Data.GetDataPresent(DataFormats.FileDrop))
          {
              e.Effect = DragDropEffects.Copy;
          }
          else
          {
              e.Effect = DragDropEffects.None;
          }
      }

To examine the code, first we have some bunch of if statements, checking for data formats. we specified that we want to change cursor when it is equal to DataFormats.FileDrop, DataFormats.Text. if you place a break point and drag a file into the control with this event it should go into the second if statement (with the DataFormats.FileDrop).

Now we want to add an event to handle the DragDrop action, this happens when a file is released(Dropped) on top of the control.

      private void listView1_DragDrop(object sender, DragEventArgs e)
      {

          if (e.Data.GetDataPresent(DataFormats.FileDrop, false) == true)
          {
              string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
// todo: validate array of files and check if this type of files are allowed on your application
// todo: do actual processing of the files given you have the file path
          }
      }

In here we only checked for, if it is a DataFormat.
if (e.Data.GetDataPresent(DataFormats.FileDrop, false) == true)

To get the files that has been DragDrop inside the control we used e.Data.GetData which is a DragEventArgs. GetData returns an object so we need to cast it to an array of string.
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);

After this we should already have the complete File path of the items being DragDropped into the control. here we do our processing/logic of the actual files which is stored in (string[] files).

that should do the trick.

Leave a Reply

Proudly powered by Blogger
Theme: Esquire by Matthew Buchanan.
Converted by LiteThemes.com.