views:

521

answers:

4

On my Asp.NET website, I have a listbox that allows multiple selections. I'd like to be able to ask something like:

blah = myListbox.selectedItems;

and be given a collection of the items that were selected in the listbox. It looks like there is a method for this in the Windows Forms world, but not for asp.NET. Is there a simpler way to do this than just iterating over the Items collection looking for selected values?

+1  A: 

Doesn't look like you can get the items directly, but GetSelectedIndices might help.

Matthew Jones
+4  A: 

Something like this should get you the selected items:

    List<ListItem> selectedItems = new List<ListItem>();
    int[] selectedItemsIndexes = myListbox.GetSelectedIndices();
    foreach (int selectedItem in selectedItemsIndexes)
    {
        selectedItems.Add(myListbox.Items[selectedItem]);
    }

As an extension method:

public static class ListBoxExtensions
{

    public static List<ListItem> GetSelectedItems(this ListBox listbox)
    {
        List<ListItem> selectedItems = new List<ListItem>();
        int[] selectedItemsIndexes = listbox.GetSelectedIndices();
        foreach (int selectedItem in selectedItemsIndexes)
        {
            selectedItems.Add(listbox.Items[selectedItem]);
        }
        return selectedItems;
    }
}

so now you can just call:

List<ListItem> selectedItems = myListBox.GetSelectedItems();


As olle suggested the Extension method could be Linq-ified and thu shrunk down even further to:

public static class ListBoxExtensions
{

    public static IEnumerable<ListItem> GetSelectedItems(this ListBox listbox)
    {
        var selectedItems = from ListItem i in myListbox.Items where i.Selected select i
        return selectedItems;
    }
}
Rob
And yeup - it iterates over the collection, but as far a I can tell there's no nicer way
Rob
+1  A: 

There is no such property but an easy linq query gets you the results fast and easy.

var selectedItems = from ListItem i in myListbox.Items where i.Selected select i;

With an extension method you can make it even simpler if you need to do this kind of thing allot.

olle
At least on my PC (could be a quirk - it's had more CTP's installed and uninstalled than I've had hot dinners!), I needed to specify the type for i so:var selectedItems = from ListItem i in myListbox.Items where i.Selected select i;
Rob
Ah no you are absolutely right. Thanks for pointing that out. I guess I shouldn't only not commit compiled code but also not answer with it. Updated the answer to be correct.
olle