I've got drag and drop to work in ListView so that I can drag a folder containing mp3's and they will display. My problem is that they only show up if I drag the directory in. I can't drag a single .mp3 file in by itself and have it displayed. I also have 2 columns setup; a Title column for the song name, and a Location column for the path. How do I get the filename (or song name) under the 'Title' column and it's path under the 'Location' column? Here's the code I have so far for the drag and drop events.

private void listView1_DragDrop(object sender, DragEventArgs e)
        {
            
            string[] directoryName = (string[])e.Data.GetData(DataFormats.FileDrop);
            //get all files inside folder            
            string[] files = Directory.GetFiles(directoryName[0]);

            listView1.Items.Clear();

            foreach (string file in files)
            {
              
                if (Path.GetExtension(file) == ".mp3")
                    listView1.Columns.Add(file);
            }        
        }

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

Thanks.

Set your listView1.View = details so you can see the column headers. Then use this code:

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

    private void listView1_DragDrop(object sender, DragEventArgs e)
    {
      listView1.Items.Clear();

      string[] handles = (string[])e.Data.GetData(DataFormats.FileDrop, false);
      foreach (string s in handles)
      {
        if (File.Exists(s))
        {
          if (string.Compare(Path.GetExtension(s), ".mp3", true) == 0)
          {
            AddFileToListview(s);
          }
        }
        else if (Directory.Exists(s))
        {
          DirectoryInfo di = new DirectoryInfo(s);
          FileInfo[] files = di.GetFiles("*.mp3");
          foreach (FileInfo file in files)
            AddFileToListview(file.FullName);
        }
      }
    }

    private void AddFileToListview(string fullFilePath)
    {
      if (!File.Exists(fullFilePath))
        return;
      string fileName = Path.GetFileName(fullFilePath);
      string dirName = Path.GetDirectoryName(fullFilePath);
      if (dirName.EndsWith(Convert.ToString(Path.DirectorySeparatorChar)))
        dirName = dirName.Substring(0, dirName.Length - 1); //hack off the trailing \
      ListViewItem itm = listView1.Items.Add(fileName);
      itm.SubItems.Add(dirName); //second column = path
    }

Ah, thanks again Scott.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.