Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将多个项目设置为在列表框中选中?_C#_Asp.net_Listbox_Selected_Listitem - Fatal编程技术网

C# 如何将多个项目设置为在列表框中选中?

C# 如何将多个项目设置为在列表框中选中?,c#,asp.net,listbox,selected,listitem,C#,Asp.net,Listbox,Selected,Listitem,我有一个列表框,选择模式为多个。在代码隐藏中,我想将一些值设置为选中值。这些值出现在名为'Names'的列表项[]中 HTML代码: <asp:ListBox ID="lbto" class="chosen" runat="server" Width="450px" Height="20px" SelectionMode="Multiple"> <asp:ListItem>Mandy</asp:ListItem> <asp:ListI

我有一个列表框,选择模式为多个。在代码隐藏中,我想将一些值设置为选中值。这些值出现在名为'Names'列表项[]

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包含'ragu''raju'。现在,当页面加载时,列表框应该包含'ragu''raju'作为所选值。

如何设置

var name=新列表(新字符串[]{“ragu”,“raju”});
foreach(lbto.Items中的var项)
{
if(名称.包含(项.文本))
item.Selected=true;
}
使用一行linq

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

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

您可以使用
FindByValue
方法

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

您可以使用上述方法将多个项目设置为选中的
。更新了答案。如果
lbto
包含100项意味着,它将检查全部100项。这会花费更多的时间吗?
foreach
意味着它将检查每个项目,或者你的意思是什么?我得到一个错误,说ListItemCollection没有“foreach”的定义,也没有扩展方法“foreach”。解决方案不起作用。我收到一个错误,说明ListItemCollection没有“ForEach”的定义,并且没有扩展方法“ForEach”System.Collection.Generic.IEnumerable不包含ForEach的定义。我使用了foreach语句。@rhose87您需要对System.Linq使用指令
lbto.Items.OfType<string>().ForEach(i => i.Selected = names.Contains(i.Text));
foreach (string item in stringList)
    lbxList.Items.FindByValue(item).Selected = true;