Alex Rivera | Logout

ASP:ListBox Get Selected Items - One Liner?

Asked 2011-12-12T18:24:32.217
10

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!!

Edit
Report

1 Answer

2
var selectedQuery = listBox.Items.Cast<ListItem>().Where(item => item.Selected); 
string selectedItems =  String.Join(",", selectedQuery).TrimEnd();
answered 2012-03-26T12:56:34.190

Your Answer