Drag and Drop File on Windows Forms

Dialog to open a file

Create a project of type “Windows Forms Application”:



On form add a textbox and a button like this:



Click twice on button “Open” to generate the click event:



Add the follow code:

  1. using (OpenFileDialog dialog = new OpenFileDialog())  
  2. {  
  3.    if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)  
  4.    {  
  5.       textBox1.Text = dialog.FileName;  
  6.    }  
  7. }  
Run your application.

Drag file from explorer to your Application

We need to set the property “allowdrop” to true on our textbox:



Now we need to implement the event DragOver on the textbox component:



At event created we need to add the follow code:

  1. private void textBox1_DragOver(object sender, DragEventArgs e)  
  2. {  
  3.    if (e.Data.GetDataPresent(DataFormats.FileDrop))  
  4.       e.Effect = DragDropEffects.Link;  
  5.    else  
  6.       e.Effect = DragDropEffects.None;  
  7. }  
The method “.Data.GetDataPresent(DataFormats.FileDrop)” check if is a File droping. In case true, we set the effect to “Link”.

Now we need to create event DragDrop on textbox:



At event created put this:

  1. private void textBox1_DragDrop(object sender, DragEventArgs e)  
  2. {  
  3.    string[] files = e.Data.GetData(DataFormats.FileDrop) as string[]; // get all files droppeds  
  4.    if (files != null && files.Any())  
  5.       textBox1.Text = files.First(); //select the first one  
  6. }  
Run your application from generated “.exe”, from debug doesn’t work.

Ebook Download
View all
Learn
View all