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?
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;
}
}
Doesn't look like you can get the items directly, but GetSelectedIndices might help.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With