9

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?

5 Answers 5

16

You will have to use FindByValue method of the ListBox

foreach (string selectedValue in SelectedValuesArray)
                    {
                        lstBranch.Items.FindByValue(selectedValue).Selected = true;
                    }
Sign up to request clarification or add additional context in comments.

2 Comments

+1 this is the best option in my opinion because it only iterates through the needed items, not the entire listbox collection. I used it in my own solution, thanks Phu!
Do we need to call DataBind Method after setting the selected property to true?
13

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

Comments

6

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.Selected = true
  end if 
Next

Comments

1

In C#:

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

Comments

0

I like where bill berlington is going with his solution. I don't want to iterate through the ListBox.Items for each item in my array. Here is my solution:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.