tags:

views:

43

answers:

3

Hi, I want to know how you can know if an item selected or not in the items array of a listbox. The listbox allows multiple selections so I need to iterate all of them and see which are selected and which are not.

Many thanks (I know - short and sweet)

A: 

ListBox has a SelectedItems property. That collection will have references to the items that have been selected.

Randolpho
yes it brings back all the selected items - but I want to look through ALL items and see if it was selected or not - I don't just want to look at selected items purely.
Vidar
@Vidar: Why not? If you're only concerned with the items that are selected, you've got that collection pre-filtered. If you really need to iterate through the entire collection and find the ones that are selected, you can do it with a `.Contains` call on the `SelectedItems`, but it sounds to me like your approach may be off. Perhaps you can explain it better and I can guide you in the right direction.
Randolpho
I think my approach may be off = not sure yet, as I am rushing this code a bit...
Vidar
A: 

I haven't worked on WPF & this is purely based on MSDN.
Look at SelectedItems propeerty.

shahkalpesh
+3  A: 

Look at the SelectedItems property, and iterate through that to see which items are selected.

If you want to go through all items you can compare the two collections (MyListBox.Items and MyListBox.SelectedItems) and see which ones match.

something like:

foreach(Item item in MyListBox.Items)        
    if(MyListBox.SelectedItems.Contains(item)
        MyObject.Value = true;
    else
        MyObject.Value = false;

Overkill though really! I guess there is a purpose if you want to do something to all items which are not selected though, is that what you are looking to do?

There are much better ways to do this though - Randolpho is correct, databinding would be a better way to go about this depending on how your data is organised/input and how big the listbox is.

Spud1
I want to do soemthing to the underlying object - if it gets selected then set a value to true - if it gets deselected then set it back to false.
Vidar
@Vidar: you should look into databinding in general and the [Model View View-Model](http://msdn.microsoft.com/en-us/magazine/dd419663.aspx) pattern in particular.
Randolpho
My solution as above would work for what you want - just add else to that if statement, and then do what you want to the object there. I'll edit my answer.
Spud1
Spud1: but it *is* overkill. @Vidar needs to consider a different approach.
Randolpho
Just tried your code - looking good.
Vidar