简体   繁体   中英

How can I get an array of all selected items in a ListBox?

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.

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 .

Here is the MS docn

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>

I think you need to look at the SelectedItems property:

    foreach (var item in listBox1.SelectedItems)
    {
        Console.WriteLine(item);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM