【问题标题】:How to set multiple items as selected in ListBox?如何设置列表框中选择的多个项目?
【发布时间】:2013-04-11 08:19:09
【问题描述】:

我有一个 ListBox 选择模式为多个。在后面的代码中,我想将一些值设置为选中。这些值存在于名为 'Names'ListItems[] 中。

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

【问题讨论】:

    标签: c# asp.net listbox selected listitem


    【解决方案1】:

    如何设置ListItemSelected 属性?

    var names = new List<string>(new string[] { "ragu", "raju" });
    
    foreach (var item in lbto.Items)
    {
        if (names.Contains(item.Text))
            item.Selected = true;
    }
    

    【讨论】:

    • 您可以使用上述方法将多个项目设置为Selected。更新了答案。
    • 如果lbto 包含100 项意味着,它将检查整个100 项。需要更多时间吗?
    • foreach 表示,它会检查每个项目,或者你是什么意思?
    【解决方案2】:

    你可以使用FindByValue方法

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

    【讨论】:

      【解决方案3】:
      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);
          }
      }
      

      【讨论】:

      • 对已得到很好回答的旧问题的新答案需要充分解释它们如何补充其他答案。
      【解决方案4】:

      使用一行 linq

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

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

      【讨论】:

      • 我收到一条错误消息,指出 ListItemCollection 没有 'ForEach' 的定义并且没有扩展方法 'ForEach'
      • 解决方案不起作用。我收到一条错误消息,说 ListItemCollection 没有“ForEach”的定义,也没有扩展方法“ForEach”
      • System.Collection.Generic.IEnumerable 不包含 Foreach 的定义。我改用了 foreach 语句。
      • @rhose87 你需要使用 System.Linq 指令
      猜你喜欢
      • 1970-01-01
      • 2021-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-23
      • 1970-01-01
      • 1970-01-01
      • 2018-12-24
      相关资源
      最近更新 更多