C#: Drag and drop files on DataGridView in a WinForm Application
Introduction
If you want to drag and drop files on a DataGridView in your WinForm (Windows Form) application and want the DataGridView to process and populate that data on it then you have come across the right article. Follow along and within minutes you will have the right idea of how to achieve that.
The Process
Step 1: Enabling AllowDrop property of the DataGridView
Go to the properties tab of your DataGridView ad enable the AllowDrop to True instead of False, as follows:
Step 2: Setting up the DragEnter event for some action
Here you check whether the data format of the file(s), which is being dragged and dropped, is in the correct format. And if the format is acceptable then you modify the drop effect on the DataGridView accordingly. In order to achieve this you need to write the following code:
private void dataGridView_DragEnter(object sender, DragEventArgs e)
{
// Check if the Data format of the file(s) can be accepted
// (we only accept file drops from Windows Explorer, etc.)
if(e.Data.GetDataPresent(DataFormats.FileDrop))
{
// modify the drag drop effects to Move
e.Effect = DragDropEffects.Move;
}
else
{
// no need for any drag drop effect
e.Effect = DragDropEffects.None;
}
}
Step 3: Finally make the DragDrop action happen here
In the DragDrop event of the DataGridView, you write your desired action of what to do when the data format of the file(s) being dropped is acceptable. Use the following code for this step:
private void dataGridView_DragDrop(object sender, DragEventArgs e)
{
// still check if the associated data from the file(s) can be used for this purpose
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
// Fetch the file(s) names with full path here to be processed
string[] fileList = (string[])e.Data.GetData(DataFormats.FileDrop);
// Your desired code goes here to process the file(s) being dropped
}
}
And TADA! You have a working Drag and Drop feature on your DataGridView in your WinForm Application.
Caution: Hot Stuff Here
Wasted 5 mins figuring out that without enabling AllowDrop property of the DataGridView this whole feature wouldn't work. So before you write the codes for DragEnter and DragDrop events do make sure that AllowDrop is enabled, or else you will also find yourself wasting few minutes just to figure out this one. Happy coding!
See Also
Control.DragDrop Event: https://msdn.microsoft.com/en-us/library/system.windows.forms.control.dragdrop(v=vs.110).aspx
Control.DragEnter Event: https://msdn.microsoft.com/en-us/library/system.windows.forms.control.dragenter(v=vs.110).aspx
DataFormats.FileDrop Field: https://msdn.microsoft.com/en-us/library/system.windows.forms.dataformats.filedrop(v=vs.110).aspx
DragEventArgs Class: https://msdn.microsoft.com/en-us/library/system.windows.forms.drageventargs(v=vs.110).aspx