C# 如何将多个项目设置为在 ListBox 中选择?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15943883/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set multiple items as selected in ListBox?
提问by ragu
I have one ListBoxwith selection mode of multiple. In code behind, I want to set some values as selected. These values are present in a ListItems[]named 'Names'.
我有一个选择模式为多个的列表框。在后面的代码中,我想设置一些选定的值。这些值存在于名为'Names'的ListItems[] 中。
HTML code:
HTML代码:
<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[] Namescontains 'ragu'and 'raju'. Now, when the page loads, the ListBoxshould contain 'ragu'and 'raju'as selected values.
列表项[]的名称中包含“肉酱”和“拉朱”。现在,页面加载时,在列表框应该包含“肉酱”和“拉朱”作为选择的值。
采纳答案by Carsten
回答by Damith
Using One line of linq
使用一行 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));
回答by Alejandro Haro
You can use FindByValue
method
你可以使用FindByValue
方法
foreach (string item in stringList)
lbxList.Items.FindByValue(item).Selected = true;