How to get selected values of a ListBox

Most of the times we do a for-loop to get all selected values or items of a ListBox. But Listbox has a method that can give all the selected items without a loop.

The method is GetSelectedIndices().

Here is an example. Say you have an ASP.NET ListBox control something like this.


 
<
asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple">
<
asp:ListItem>1</asp:ListItem>
<
asp:ListItem>2</asp:ListItem>
<
asp:ListItem>3</asp:ListItem>
</
asp:ListBox>

You can get all selected items in your code using the following code snippet.
ListBox1.GetSelectedIndices();
GetSelectedIndices gives us the index of all selected items in the ListBox.

Note: The output is in array collections.