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!!
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Using LINQ:
string values = String.Join(", ", lbAppGroup.Items.Cast<ListItem>()
.Where(i => i.Selected)
.Select(i => i.Value));
Method 2
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);
Method 3
var selectedQuery = listBox.Items.Cast<ListItem>().Where(item => item.Selected);
string selectedItems = String.Join(",", selectedQuery).TrimEnd();
Method 4
Actually there IS something built in:
ListBox.getSelectedItems
http://msdn.microsoft.com/en-us/library/aa297606(v=vs.60).aspx
Method 5
Another way is to use the Request Form object which contains everything that was posted back. eg:
string values = Request.Form(lbAppGroup.UniqueID); //returns "a,b" if they were selected
This by default returns a comma delimited list of selected items.
I sometimes use this way when I don’t want or need to bind the data again but still want to get the selected values for processing.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0