views:

180

answers:

3

I have a ListBox in a WinForm with multiselect enabled.

The selected items appear to be stored in an object, how to I get their values?

A: 

Try the SelectedItems property.

foreach (var selectedItem in listBox1.SelectedItems)
{
    ...
}
0bj3ct.m3th0d
+2  A: 

Easy, depending on what type you stored:

foreach (MyItemType item in listBox1.SelectedItems)
{
   ...
}

Because this is an older, non-generic collection it is better not to use var to declare the item variable. That would only get you a reference of type object.

You can also use other properties like:

if (listBox1.SelectedItems.Count > 0)
   ...
Henk Holterman
A: 

The selected items are found in the SelectedItems property. These are the objects that you added to the list box, so you can cast the objects to their respective type and access any members that way:

// get the first selected item, cast it to MyClass
MyClass item = listBox.SelectedItems[0] as MyClass;
if (item != null)
{
    // use item here
}
Fredrik Mörk
This would get the first/single selection, but it still needs to check the size of the `SelectedItems` collection, otherwise no selection will make this throw index out of bounds.
Jon Seigel
@Jon: you are of course correct. My answer is not an attempt to be a complete guide on how to use the `SelectedItems` property, but rather to answer the question *The selected items appear to be stored in an object, how to I get their values*.
Fredrik Mörk
@Fredrik: Fair enough. I just wanted to add a small warning for anyone tempted to copy/paste this code.
Jon Seigel
@Jon: And a good (and important) one it was :)
Fredrik Mörk