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.
Suthish NairTOP 100Posted Aug 29, 2010, 11:28 AM EDT
While using GetSelectedIndices(), duplicate values in ListBox is not supported. You can add them, but the framework always uses only the first matching list item value. You can test the code by adding duplicate items in ListBox.
Suthish NairTOP 100Posted Aug 29, 2010, 11:16 AM EDT
GetSelectedIndices() - Gets the array of index values for currently selected items in the ListBox control.
We can avoid looping the whole items to find the selected item.
If we need the selected items for further use, of course we need to loop the records. :-)
Mahesh ChandTOP 10Posted Aug 29, 2010, 8:32 AM EDT
Even though you get index of all selected items, you still have to loop through to get all items. Don't you?
Suthish NairTOP 100Posted Aug 29, 2010, 11:28 AM EDT
While using GetSelectedIndices(), duplicate values in ListBox is not supported. You can add them, but the framework always uses only the first matching list item value. You can test the code by adding duplicate items in ListBox.
Suthish NairTOP 100Posted Aug 29, 2010, 11:16 AM EDT
GetSelectedIndices() - Gets the array of index values for currently selected items in the ListBox control. We can avoid looping the whole items to find the selected item. If we need the selected items for further use, of course we need to loop the records. :-)
Mahesh ChandTOP 10Posted Aug 29, 2010, 8:32 AM EDT
Even though you get index of all selected items, you still have to loop through to get all items. Don't you?