DataGridView Drag and Drop with Multiple Files

13. January 2010

I was working on a project tonight and I noticed something kind of odd. There are a ton of references out there for how to handle the DragDrop event with a single file, but I wasn’t able to find really anything about handling multiple files. Needless to say I figured I’d make a post to remedy this problem.

First thing to note is to select the DataGridView in the designer and from the properties window set “Allow Drop” to “True" to enable the events. Second is to add an event handler to the DataGridView DragEnter event. Within the event simply set e.Effect to one of the desired DragDropEffects enumeration values as such:

private void dgvImageFiles_DragEnter(object sender, DragEventArgs e)
{
     e.Effect = DragDropEffects.Copy;
}

The next step is to simply add an event handler for the DragDrop event and use e.Data.GetData(“FileDrop”) to get a string array containing the full file paths to each file dropped into the DataGridView control. That was at least my desire when building this code, but you could just as easily handle any of the other data format values available from e.Data.GetFormats() function. Below is the DragDrop event I’ve used to get the files dropped into the DataGridView control:

        private void dgvImageFiles_DragDrop(object sender, DragEventArgs e)
        {            
            if (e.Data.GetDataPresent("FileDrop"))
            {
                string[] files = (e.Data.GetData("FileDrop") as string[]);
 
                foreach (string file in files)
                {
                    . . . 
                }
            }
        }

That is how to handle drag and drop with the DataGridView with multiple files. Easy enough eh? Well then back to programming I go.

.Net, Programming

Add comment




biuquote
  • Comment
  • Preview
Loading