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






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 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.