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();
Share:
13,362
turtlepower
Author by

turtlepower

Updated on June 13, 2022

Comments

  • turtlepower
    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
    turtlepower over 13 years
    Thank 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
    Yogesh over 13 years
    5 items as in selected items? Can you post the code you are using to "return them"?
  • turtlepower
    turtlepower over 13 years
    List<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
    turtlepower over 13 years
    Ahh, 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
    turtlepower over 13 years
    Update: 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
    Vincent almost 3 years
    Your solution doesn't work if items are simple strings - "IndexOf" will return FIRST match if you have duplicate strings.