Reputation: 11
I have a ListBox
that lists all of the .mp3
files in a directory. The program allows the user to select some of those .mp3
files and edit the ID3 tags (file properties - like artist, album, title, etc..) easily. However, I can't find the way I can get an array of all the items selected by the user rather than just one.
I've seen how to get the one selected item (listBox.SelectedValue
), but I will often have more than one selected item as I'm using MultiSimple
for the selection mode property (allowing me to select multiple items rather than just one). As far as I can see, there's no way to do something like listBox.SelectedValue[2]
or listBox.Item.IndexOf(2).Selected()
.
string[] selectedItems = new string[allMusicBox.SelectedItems.Count];
// A count of how many items have been added to the selected items array
int addedSelectedItems = 0;
for (int i = 0; i < allMusicBox.Items.Count; i++) {
if (allMusicBox.Items.IndexOf(i).Selected) {
selectedItems[addedSelectedItems] = allMusicBox.Items.IndexOf(i).ToString();
addedSelectedItems++;
}
}
That code right there doesn't actually work, but that's along the lines of what I'm looking for. I'm wondering how to check whether that item (at the position of 'i') is selected, and then if it is, add it to the 'selectedItems' array.
Upvotes: 0
Views: 755
Reputation: 663
I think you need to look at the SelectedItems property:
foreach (var item in listBox1.SelectedItems)
{
Console.WriteLine(item);
}
Upvotes: 0
Reputation: 7282
The SelectedItems
property is a collection of all the selected items. You don't need to iterate through all of the items to see if they are selected, as you can just use allMusicBox.SelectedItems
.
If you really need to convert the collection to a list, then check out this SO question/answer Fastest Convert from Collection to List<T>
Upvotes: 2