How do I repesent a single item in a list box in a foreach statement?
I have tried ListBoxItem but System.Windows.Controls is not considered a valid namespace in my .Net framework (version 4).
foreach(ListBoxItem item in listBoxObject.Items)
{
...
}
Typically when someone is looping through listbox items they are looking to determine if they are selected or not. If this is the case, please try using listBoxObject.SelectedItems instead of listBoxObject.Items. This will return only items that have been selected.
As far as I can tell, there is no ListBoxItem object. You will need to use the Object for each item (which is what seletecteditems and items returns). The Object represents the item’s value, so use it accordingly (meaning, if the object is a string, use it as a string, but if an object is a complex object, use it as such).
Code Sample:
And if you know what object will ALWAYS be you can cast it in the foreach loop. (Warning: If you’re wrong this will throw an exception). This example is if only Strings are entered into the listbox.