I was debugging a co-workers program and ran across this issue in WPF.
It looks like the listBoxName.SelectedItems returns a list of selected items, in the order a user selects the item from the interface. This is a problem because I need to preserve the actual order the items.
Example:
the listbox is in Extended selectmode and my listbox contains something: runfirst, runsecond, runthird
the user is given an option to select what they want to run based from the listbox. They select runthird then runfirst. This causes runthird to appear at the top of the list and then runfirst. I guess i could sort the list before running a foreach but i was wondering if there is an easier way.
Thanks
To retrieve a collection containing all selected items in a multiple-selection ListBox, use the SelectedItems property. If you want to obtain the index position of the currently selected item in the ListBox, use the SelectedIndex property.
you can determine the selected item(s) in the ListBox control by enumerating the Items collection and testing the Selected value for each ListItem element. Save this answer.
In a single-selection ListBox control, you can retrieve the selected item by using the SelectedItem property, and its index by using the SelectedIndex property. SelectedItem returns the selected item, which is an object.
What I did was use LINQ to return the selected items in index order. It is in VB.Net syntax, but it should be easy to fix up for C#.
Dim selecteditems = From selecteditem As ListBoxItem In ListBox1.SelectedItems _
Select selecteditem _
Order By ListBox1.Items.IndexOf(selecteditem)
Yeah I ended up iterating over all the items in the in the listbox and then checked if it was in selecteditems using contains as below
foreach (<yourobject> item in listForSelection.Items)
{
if (listForSelection.SelectedItems.Contains(item))
{
\\code here
}
}
Thanks for the help guys
I think you gave the answer in your question.
Most of the time the order of selected items won't matter. Since it does for you, sorting the selected items before processing them seems to be the simplest solution. I can't really think of a simpler one, especially when the sorting should only add 1 line.
You can use the same Comparison<T>
or IComparer<T>
that was used to sort the original list. If you're binding to SelectedItems
, you can use an IValueConverter
to do the sorting.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With