views:

31

answers:

3

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)
{
    ...
}
+1  A: 

foreach(Object item in listBoxObject.Items){ ... }

http://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.objectcollection.item.aspx

ListBox.Items is of type System.Windows.Forms.ListBox.ObjectCollection System.Windows.Forms.ListBox.ObjectCollection.Item is of type Object. HTH.

Vulcan Eager
My problem with using Object type is that I want to interact with "item" as a listbox item. The following code will not work unless I make "item" be recognized as a list box item. Code snippet: foreach (Object item in listBoxObject.Items) { if (item.Selected) listBoxObject2.Add(item.Value); }
Jesslyn
A: 

You'll find that listBoxObject.Items is an object collection, containing your data objects rather than controls.

For example, if I bind the list box like so:

listBox1.DataSource = new string[] { "asdf", "qwerty" };

Then the .Items property yields an ObjectCollection containing two strings.

kbrimington
+1  A: 

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:

foreach (Object listBoxItem in listBoxObject.SelectedItems)
{
  //Use as object or cast to a more specific type of object.
}

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.

foreach (String listBoxItem in listBoxObject.SelectedItems)
{
  //Use as String. It has already been cast. 
}
Rick
Thanks! I especially needed to know there was no object type for list box items! Seems silly that you can have a collection of them but not a single entity.
Jesslyn