[英]How to set multiple items as selected in ListBox?
I have one ListBox with selection mode of multiple.我有一个具有多种选择模式的ListBox 。 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[] Names contains 'ragu' and 'raju' . ListItem[] 名称包含'ragu'和'raju' 。 Now, when the page loads, the ListBox should contain 'ragu' and 'raju' as selected values.
现在,当页面加载时, ListBox应该包含'ragu'和'raju'作为选定值。
You can use FindByValue
method 您可以使用
FindByValue
方法
foreach (string item in stringList)
lbxList.Items.FindByValue(item).Selected = true;
int[] IndexList = new int[] { 1, 3, 5, 7, 9 };
for (int i = 0; i < IndexList.Length; i++)
{
if (listBox1.Items.Count > IndexList[i])
{
listBoxFX.SetSelected(IndexList[i], true);
}
}
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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.