Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP:ListBox Get Selected Items - One Liner?

I am trying to get the selected items of an asp:ListBox control and put them in a comma delimited string. There has got to be a simpler way of doing this then:

foreach (ListItem listItem in lbAppGroup.Items)
{
    if (listItem.Selected == true)
    {
        Trace.Warn("Selected Item", listItem.Value);
    }
}

Is there a way to get this into one line? like my pseudo code here:

string values = myListBox.SelectedItems;

I am using ASP.NET and C# 3.5.

Thanks for any help!!

like image 999
Jared Avatar asked Dec 12 '11 18:12

Jared


3 Answers

Using LINQ:

string values = String.Join(", ", lbAppGroup.Items.Cast<ListItem>()
                                                  .Where(i => i.Selected)
                                                  .Select(i => i.Value));
like image 145
James Avatar answered Nov 20 '22 16:11

James


I don't think there is anything built in but you could do something like this:

  <asp:ListBox runat="server" ID="listBox" SelectionMode="Multiple">
    <asp:ListItem Selected="True" Text="text1" Value="value1"></asp:ListItem>
    <asp:ListItem Selected="false" Text="text2" Value="value2"></asp:ListItem>
    <asp:ListItem Selected="True" Text="text3" Value="value3"></asp:ListItem>
    <asp:ListItem Selected="True" Text="text4" Value="value4"></asp:ListItem>
</asp:ListBox>

    IEnumerable<string> selectedValues = from item in listBox.Items.Cast<ListItem>()
                                             where item.Selected
                                             select item.Text;

        string s = string.Join(",", selectedValues);
like image 42
Dave Avatar answered Nov 20 '22 15:11

Dave


var selectedQuery = listBox.Items.Cast<ListItem>().Where(item => item.Selected); 
string selectedItems =  String.Join(",", selectedQuery).TrimEnd();
like image 2
Rami Sarieddine Avatar answered Nov 20 '22 16:11

Rami Sarieddine