July 26, 2009

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



'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP 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 has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

5 Responses to "Programmatically Select Multiple Items of an ASP.NET ListBox"
  1. rtpHarry said...
    July 27, 2009 1:18 AM

    c# code sample is busted (if statement)

  2. Suprotim Agarwal said...
    July 27, 2009 8:38 AM

    Thanks rptHarry! Its fixed now

  3. Jukebox said...
    July 27, 2009 8:56 AM

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

  4. Suprotim Agarwal said...
    July 27, 2009 9:08 AM

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

    Retrieve Selected Items of an ASP.NET ListBox using LINQ

    HTH

  5. bhaskar said...
    April 23, 2010 5:23 AM

    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.

 

Copyright © 2009-2012 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions