I am currently working on my own MP3 player and want to add drag & drop functionality to be able to drag & drop your music either a file at a time or a whole directory at a time. I have the View of my ListView set to details, and am using the following code:
void Playlist_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
e.Effect = DragDropEffects.Copy;
}
void Playlist_DragDrop(object sender, DragEventArgs e)
{
Playlist.Items.Clear();
string[] songs = (string[])e.Data.GetData(DataFormats.FileDrop, false);
Parallel.ForEach(songs, s =>
{
if (File.Exists(s))
{
if (string.Compare(Path.GetExtension(s), ".mp3", true) == 0)
{
MessageBox.Show(s);
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);
MessageBox.Show(file.FullName);
}
}
});
}
private void AddFileToListview(string fullFilePath)
{
if (!File.Exists(fullFilePath))
return;
string song = Path.GetFileName(fullFilePath);
string directory = Path.GetDirectoryName(fullFilePath);
if (directory.EndsWith(Convert.ToString(Path.DirectorySeparatorChar)))
directory = directory.Substring(0, directory.Length - 1); //hack off the trailing \
ListViewItem itm = Playlist.Items.Add(song);
itm.SubItems.Add(directory); //second column = path
}
I have the MessageBox in there to make sure my code is being hit and tit always shows me the right data but nothing shows in the ListView. Any ideas what I'm doing wrong?
@ClearLogic: You were right I forgot to define columns in the ListView, thanks. Now I have another problem, I can drag multiple directories into the ListView with no problems, but when I try to add multiple single MP3's I get a cross-thread exception on the line
ListViewItem itm = Playlist.Items.Add(song);