views:

659

answers:

2

I can't find a way to select multiple items in an ASP.NET ListBox in the code behind? Is this something needs to be done in Javascript?

+1  A: 

this is the VB code to do so...

myListBox.SelectionMode = Multiple
For each i as listBoxItem in myListBox.Items
  if i.Value = WantedValue Then
      i.Select = true
  end if 
Next
Stephen Wrighton
i.Selected = true
Tony_Henrich
+1  A: 

Here's a C# sample


(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>

(Code Behind)

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;
          }
     }
}
Bob