Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an ASP.NET collection for selected items in ListBox?

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?

like image 370
Beska Avatar asked Dec 23 '22 09:12

Beska


2 Answers

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;
    }
}
like image 108
Rob Avatar answered Dec 24 '22 21:12

Rob


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

like image 26
Matthew Jones Avatar answered Dec 24 '22 22:12

Matthew Jones