如何在ASP.NET ListBox中设置多个选择?

Ton*_*ich 9 asp.net listbox

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

Rob*_*ert 13

这是一个C#样本


(Java)

<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>
Run Code Online (Sandbox Code Playgroud)

(代码背后)

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;
          }
     }
}
Run Code Online (Sandbox Code Playgroud)


Bal*_*dar 13

您将不得不使用ListBox的FindByValue方法

foreach (string selectedValue in SelectedValuesArray)
                    {
                        lstBranch.Items.FindByValue(selectedValue).Selected = true;
                    }
Run Code Online (Sandbox Code Playgroud)

  • 我认为+1是最好的选择,因为它只会遍历所需的项,而不遍历整个列表框集合。我在自己的解决方案中使用了它,谢谢Phu! (2认同)

Ste*_*ton 7

这是VB代码,这样做......

myListBox.SelectionMode = Multiple
For each i as listBoxItem in myListBox.Items
  if i.Value = WantedValue Then
      i.Selected = true
  end if 
Next
Run Code Online (Sandbox Code Playgroud)