Getting the index of multiple selected items in a listbox using Silverlight
13,362
You can find the selected indexes by iterating through SelectedItems
and finding the objects in the Items
property, like this:
List<int> selectedItemIndexes = new List<int>();
foreach (object o in listBox.SelectedItems)
selectedItemIndexes.Add(listBox.Items.IndexOf(o));
Or if you prefer linq:
List<int> selectedItemIndexes = (from object o in listBox.SelectedItems select listBox.Items.IndexOf(o)).ToList();
Author by
turtlepower
Updated on June 13, 2022Comments
-
turtlepower almost 2 years
I have a ListBox which is made up of Grid Items in Multiple SelectionMode in Silverlight 3.0.
When I use ListBox.SelectedIndex it only returns the first item which is selected.
I would like to be able see all of the selected items such that it would return all of the selected item indexes' such as; 2, 5, and 7, etc.
Any help?
Cheers,
Turtlepower.
-
turtlepower over 13 yearsThank you Yogesh, it's nearly working. Strangely I have only 5 Items in my listbox and when I return them all I get 7 items which goes "0, 1, 2, 3, 4, 0, 0, 0". Why the extra three 0's on the end?
-
Yogesh over 13 years5 items as in selected items? Can you post the code you are using to "return them"?
-
turtlepower over 13 yearsList<int> selectedItemIndexes = new List<int>(); foreach (object o in myListBox.SelectedItems) { selectedItemIndexes.Add(myListBox.Items.IndexOf(o)); } Yes, 5 items and I only select 5 items too. Odd.
-
turtlepower over 13 yearsAhh, as in when I am in the debugger and open up the List collection I see a trailing end of 0's after the selected items.
-
turtlepower over 13 yearsUpdate: doesn't seem to do it when I actually return the selectedItemsIndexes[i], must just be a trail off thing. Thanks for the help!
-
Vincent almost 3 yearsYour solution doesn't work if items are simple strings - "IndexOf" will return FIRST match if you have duplicate strings.