14

Anyone know of a smooth way to get all of the selected items in a listbox control by using extension methods?

And, please, spare me the argument of it's irrelevant as to how one gets such a list because in the end everything uses a loop to iterate over the items and find the selected ones anyway.

Jagd
  • 7,169
  • 22
  • 74
  • 107

3 Answers3

29
var selected = yourListBox.Items.GetSelectedItems();
//var selected = yourDropDownList.Items.GetSelectedItems();
//var selected = yourCheckBoxList.Items.GetSelectedItems();
//var selected = yourRadioButtonList.Items.GetSelectedItems();

public static class Extensions
{
    public static IEnumerable<ListItem> GetSelectedItems(
           this ListItemCollection items)
    {
        return items.OfType<ListItem>().Where(item => item.Selected);
    }
}
Rubens Farias
  • 57,174
  • 8
  • 131
  • 162
7

Extension method:

public static List<ListItem> GetSelectedItems(this ListBox lst)
{
    return lst.Items.OfType<ListItem>().Where(i => i.Selected).ToList();
}

You can call it on your listbox like:

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

You could also do the conversion using a 'Cast' on the list box items like:

return lst.Items.Cast<ListItem>().Where(i => i.Selected).ToList();

Not sure which will perform better OfType or Cast (my hunch is Cast).

Edit based on Ruben's feedback for a generic ListControl method which would indeed make it much more useful extension method:

public static List<ListItem> GetSelectedItems(this ListControl lst)
{
    return lst.Items.OfType<ListItem>().Where(i => i.Selected).ToList();
}
Kelsey
  • 47,246
  • 16
  • 124
  • 162
  • You could also to replace `ListBox` for `ListControl`, so your extension works for all list controls, as `DropDownList`, `CheckBoxList`, `RadioButtonList` and so on – Rubens Farias Dec 02 '09 at 00:48
  • Good idea.. will adjust my answer to reflect that. – Kelsey Dec 02 '09 at 00:58
  • `Cast` is a bit faster, but can lead to `InvalidCastException`; seems Cast is applicable here, since `Items.Add` just receive `ListItem` objects – Rubens Farias Dec 02 '09 at 01:08
1

Hello i've created one solution for this problem in this post using VB.NET:

Getting all selected values from an ASP ListBox

This code below is the same as the link above:

Public Shared Function getSelectedValuesFromListBox(ByVal objListBox As ListBox) As String
Dim listOfIndices As List(Of Integer) = objListBox.GetSelectedIndices().ToList()
Dim values As String = String.Empty

For Each indice As Integer In listOfIndices
    values &= "," & objListBox.Items(indice).Value
Next indice
If Not String.IsNullOrEmpty(values) Then
    values = values.Substring(1)
End If
Return values
End Function

I hope it helps.

oviniciusfeitosa
  • 915
  • 1
  • 11
  • 12
  • Your first line doesn't compile in VS2015 for me; but replacing it with Dim listOfIndices() As Integer = objListBox.GetSelectedIndices() seems to do the trick – DJDave Nov 11 '16 at 18:06