I'm loading music playlist from disk to C# ListView control. I'm using ListViewGroups to separate albums, and there can be several albums in playlist.
Playlists are saved in following text format: (not the greatest way, I know, but works for this example)
|album|name of album
track 1 fsdfsfasf.mp3
track 2 fdsgfgfdhhh.mp3
track 3 gfdgsdgsdfgs.mp3
When I'm loading playlist to ListView, I test if string "|album|" is found from the beginning of line, and use that line for group header text. Code sample below:
using (StreamReader reader = File.OpenText("playlist.txt"))
{
while (reader.Peek() >= 0)
{
result = reader.ReadLine();
if (result.Substring(0, 7) == "|album|")
{
ListViewGroup group = new ListViewGroup();
group.Header = result.Substring(7);
lstPlaylist.Groups.Add(group); // lstPlaylist is existing ListView control for playlist
}
else
{
ListViewItem item = new ListViewItem(result, 0, group);
lstPlaylist.Items.Add(item);
}
}
}
If "|album|" string is found, then I create new ListViewGroup. But that group is inaccessible inside else-statement (I can't assign item to group), because it's out of scope. How can I create new ListViewGroup inside if-statement and use it outside that if-statement?
You need to declare the variable outside the if statement so that it is available in the else clause. You also need to handle the case when a track is found before an album, unless you have already validated the source file.