How to set multiple items as selected in ListBox?

放肆的年华 提交于 2019-12-06 02:57:35

问题


I have one ListBox with selection mode of multiple. In code behind, I want to set some values as selected. These values are present in a ListItems[] named 'Names'.

HTML code:

<asp:ListBox ID="lbto" class="chosen" runat="server" Width="450px" 
 Height="20px" SelectionMode="Multiple">
    <asp:ListItem>Mandy</asp:ListItem>
    <asp:ListItem>Amit</asp:ListItem>
    <asp:ListItem>sundar</asp:ListItem>
    <asp:ListItem>ragu</asp:ListItem>
    <asp:ListItem>raju</asp:ListItem>
</asp:ListBox>

ListItem[] Names contains 'ragu' and 'raju'. Now, when the page loads, the ListBox should contain 'ragu' and 'raju' as selected values.


回答1:


What about setting the Selected-property of the ListItem?

var names = new List<string>(new string[] { "ragu", "raju" });

foreach (var item in lbto.Items)
{
    if (names.Contains(item.Text))
        item.Selected = true;
}



回答2:


You can use FindByValue method

foreach (string item in stringList)
    lbxList.Items.FindByValue(item).Selected = true;



回答3:


Using One line of linq

lbto.Items.Cast<String>().ForEach(i => i.Selected = names.Contains(i.Text));

OR

lbto.Items.OfType<string>().ForEach(i => i.Selected = names.Contains(i.Text));


来源:https://stackoverflow.com/questions/15943883/how-to-set-multiple-items-as-selected-in-listbox

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