Saturday, December 19, 2009

Drag’n Drop files in WinForms

Recently I have been playing a little bit with drag and drop functionality and this short article shows how to implement drag and drop for files in WinForms.

The first thing is to set the AllowDrop property to true for the control we are going to drop files, without it drag'n drop events are not fired. I have used ListView control listView1 to display some basic file information about the dragged file e.g. file name, path and size. To make it more fun lets allow dropping multiple files at the same time, which is a standard Windows behavior.

Next thing is create DragEnter event handler in which dragged data is being checked and Effect property is set. You might want to add some conditions e.g. allowing files with certain extension.

It may look something like this:

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


Now is the time for the DragDrop event handler, in which the file names are retreived from the dragged files and passed to the method which does the rest of job i.e. adds data to the listView1 control.

private void listView1_DragDrop(object sender, DragEventArgs e)
{
    try
    {
        if (e.Effect == DragDropEffects.Copy)
        {
            string[] fileNames = e.Data.GetData(DataFormats.FileDrop) as string[];
            if (fileNames != null)
            {
                foreach (string s in fileNames)
                {
                    Console.WriteLine(s);
                    AddFileInfoToTheListBox(s);
                }
            }
        }
    }
    catch (Exception exception)
    {
        Console.WriteLine("Exception in listBox1_DragDrop: " + exception.Message);
    }
}

Here is the AddFileInfoToTheListView method definition. It might be not the most elegant way of handling data but for the purpose of this example it is fine. To get information from the dragged file the FileInfo class is used.

private void AddFileInfoToTheListView(string fileName)
{
    try
    {
        FileInfo fi = new FileInfo(fileName);
        string [] fileData = { fi.Name, fi.ToString(),fi.Length.ToString() };
        ListViewItem lvi = new ListViewItem(fileData);
        this.listView1.Items.Add(lvi);

    }
    catch (Exception exception)
    {
        Console.WriteLine("Exception in AddFileInfoToTheListView: " + exception.Message);

    }

}

And here is the final result