【问题标题】:How to set multiple selections in ASP.NET ListBox?如何在 ASP.NET ListBox 中设置多项选择?
【发布时间】:2017-08-02 16:10:45
【问题描述】:

我在后面的代码中找不到在 ASP.NET ListBox 中选择多个项目的方法?这是需要在 Javascript 中完成的事情吗?

【问题讨论】:

    标签: asp.net listbox


    【解决方案1】:

    你必须使用 ListBox 的 FindByValue 方法

    foreach (string selectedValue in SelectedValuesArray)
                        {
                            lstBranch.Items.FindByValue(selectedValue).Selected = true;
                        }
    

    【讨论】:

    • +1 在我看来这是最好的选择,因为它只遍历所需的项目,而不是整个列表框集合。我在自己的解决方案中使用了它,谢谢 Phu!
    【解决方案2】:

    这是一个 C# 示例


    (aspx)

    <form id="form1" runat="server">
            <asp:ListBox ID="ListBox1" runat="server" >
                <asp:ListItem Value="Red" />
                <asp:ListItem Value="Blue" />
                <asp:ListItem Value="Green" />
            </asp:ListBox>
            <asp:Button ID="Button1" 
                        runat="server" 
                        onclick="Button1_Click" 
                        Text="Select Blue and Green" />
    </form>
    

    (代码隐藏)

    protected void Button1_Click(object sender, EventArgs e)
    {
         ListBox1.SelectionMode = ListSelectionMode.Multiple;            
         foreach (ListItem item in ListBox1.Items)
         {
              if (item.Value == "Blue" || item.Value == "Green")
              {
                   item.Selected = true;
              }
         }
    }
    

    【讨论】:

      【解决方案3】:

      这是执行此操作的 VB 代码...

      myListBox.SelectionMode = Multiple
      For each i as listBoxItem in myListBox.Items
        if i.Value = WantedValue Then
            i.Selected = true
        end if 
      Next
      

      【讨论】:

        【解决方案4】:

        在 C# 中:

        foreach (ListItem item in ListBox1.Items)
        {
            item.Attributes.Add("selected", "selected");
        }
        

        【讨论】:

          【解决方案5】:

          我喜欢bill berlington 的解决方案。我不想遍历数组中每个项目的 ListBox.Items。这是我的解决方案:

          foreach (int index in indicesIntArray)
          {
              applicationListBox.Items[index].Selected = true;
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2013-08-08
            • 1970-01-01
            • 2011-05-26
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多