Programmatically Select Multiple Items of an ASP.NET ListBox

In one of the forums, a user recently asked how to select multiple items of an ASP.NET ListBox. Here’s how

<div>
<
asp:ListBox ID="ListBox1" runat="server">
<
asp:ListItem Value="One" />
<
asp:ListItem Value="Two" />
<
asp:ListItem Value="Three" />
<
asp:ListItem Value="Four" />
<
asp:ListItem Value="Five" />
</
asp:ListBox>
</
div>

C#

protected void Page_Load(object sender, EventArgs e)
{
ListBox1.SelectionMode = ListSelectionMode.Multiple;
for (int i = 0; i < ListBox1.Items.Count; i++)
{
if(i == 0 || i == 2 || i == 4)
{
ListBox1.Items[i].Selected = true;
}
}
}

VB.NET

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
ListBox1.SelectionMode = ListSelectionMode.Multiple
For i As Integer = 0 To ListBox1.Items.Count - 1
If i = 0 OrElse i = 2 OrElse i = 4 Then
ListBox1.Items(i).Selected = True
End If
Next
i
End Sub

The code shown above selects the first, third and fifth items of a ListBox as in the screenshot below

image



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

5 comments:

rtpHarry said...

c# code sample is busted (if statement)

Suprotim Agarwal said...

Thanks rptHarry! Its fixed now

Jukebox said...

Handy. Can i also get list of selected items using pure LINQ?

Suprotim Agarwal said...

JukeBox: I quickly created a sample and put it over here

Retrieve Selected Items of an ASP.NET ListBox using LINQ

HTH

bhaskar said...

Hi ,

I want to get the selected items from list box(multiple items) and need to store it on collection.

List aa = new List();
foreach (ListBoxItem Li in lstUnit.SelectedItems)
{
aa.Add(Li.Name);

}

I was trying with this coede and not able to get it ,could any body help it out.