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:
- using (OpenFileDialog dialog = new OpenFileDialog())
- {
- if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
- {
- textBox1.Text = dialog.FileName;
- }
- }
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:
- private void textBox1_DragOver(object sender, DragEventArgs e)
- {
- if (e.Data.GetDataPresent(DataFormats.FileDrop))
- e.Effect = DragDropEffects.Link;
- else
- e.Effect = DragDropEffects.None;
- }
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:
- private void textBox1_DragDrop(object sender, DragEventArgs e)
- {
- string[] files = e.Data.GetData(DataFormats.FileDrop) as string[];
- if (files != null && files.Any())
- textBox1.Text = files.First();
- }
Run your application from generated “.exe”, from debug doesn’t work.