ASP:ListBox Get Selected Items - One Liner?

落爺英雄遲暮 提交于 2019-11-29 04:04:13

Using LINQ:

string values = String.Join(", ", lbAppGroup.Items.Cast<ListItem>()
                                                  .Where(i => i.Selected)
                                                  .Select(i => i.Value));

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);
var selectedQuery = listBox.Items.Cast<ListItem>().Where(item => item.Selected); 
string selectedItems =  String.Join(",", selectedQuery).TrimEnd();

Actually there IS something built in:

ListBox.getSelectedItems

http://msdn.microsoft.com/en-us/library/aa297606(v=vs.60).aspx

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!