Sanchaita Chakraborty
Sanchaita Chakraborty

Reputation: 437

Drag and drop functionality in List Box in c#

I am using list box control. I am able to drag and drop files in the list box. I have added the following code for the above.

 private void lstPDFFiles_DragEnter(object sender, DragEventArgs e)
    {
        //int i;
        if (e.Data.GetDataPresent(DataFormats.FileDrop))
            e.Effect = DragDropEffects.All;
        else
            e.Effect = DragDropEffects.None;

    }

    private void lstPDFFiles_DragDrop(object sender, DragEventArgs e)
    {
        string[] s = (string[])e.Data.GetData(DataFormats.FileDrop, false);
        int i;
        for (i = 0; i < s.Length; i++)
             lstPDFFiles.Items.Add(s[i]);

    }

This much of code allows me to drag and drop 1 file in the list box. But now i also want to allow the user to drag and drop a folder. How do i do this . Thanx a lot in advanced. Please help.

Upvotes: 2

Views: 2955

Answers (1)

Justin
Justin

Reputation: 686

This could help you!

if (e.Data.GetDataPresent(DataFormats.FileDrop))
        {
            string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
            foreach (string file in files)
            {
                if (Directory.Exists(file))
                {
                    string[] filenames = Directory.GetFiles(file);
                    foreach (string filename in filenames)
                    {
                        GetFiles(filename);
                    }
                }
                GetFiles(file);
            }
        }

    private void GetFiles(string file)
    {
        FileInfo fi = new FileInfo(file);
        listView1.Items.Add(fi.Name);
        listView1.Items[listView1.Items.Count - 1].SubItems.Add("test");
    }

Upvotes: 2

Related Questions