Reputation: 566
I am using VB. How to select mult items in listbox frombackend code?
Below, I have a listbox where user can select muti items.
<asp:ListBox ID="lb" SelectionMode="multiple" runat="server" DataValueField="dv">
<asp:ListItem>red r</asp:ListItem>
<asp:ListItem>blue b</asp:ListItem>
<asp:ListItem>green g</asp:ListItem>
</asp:ListBox>
What I have tierd so far:
How can I set so the value of "blue b" and "green g" is already selected? I tried setSelected but this method is not supported
lb.SetSelected(1, True)
lb.SetSelected(2, True)
I also tried this below which kind of works. It does select 1 value but I need to able to select multi values.
lb.Text = "blue b"
lb.Text = "green g"
I tried this also and it doesn't select any values.
lb.Text = "blue b green g"
Upvotes: 0
Views: 305
Reputation: 1473
Try using this loop. You need to change the hard-coded blue b value for a variable. I responded to a similar post that I thought was .Net instead of ASP.net. The SetSelected method is not available in ASP.net.
For Loop:
For i As Integer = 0 To listbox.Items.Count - 1 Step 1
If listbox.Items(i).Value = "blue b" Then
listbox.Items(i).Selected = true
End If
Next
For Each Loop:
For Each item As ListItem In ListBox.Items
If item.Value = "blue b" Then
item.Selected = True
End If
Next
You could also try this without a loop:
I would say this is the preferred method because you can just loop through your list of values you want selected and use this line of code. All you need to change is the string inside FindByValue.
listbox.Items(listbox.Items.IndexOf(listbox.Items.FindByValue("blue b"))).Selected = True
Upvotes: 1
Reputation: 26343
This should do the trick:
lb.Items(1).Selected = True
lb.Items(2).Selected = True
And in your postback code, get the user-selected values with lb.GetSelectedIndices
.
Upvotes: 0