Getting selected items from WinForm ListBox?

I have a ListBox in WinForm with multiselect enabled.

The selected elements are displayed in the object, how can I get their values?

+3
source share
4 answers

Easy, depending on what type you saved:

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

Since this is an older, non-general collection, it is best not to use varan element variable to declare. This will give you a type link object.

You can also use other properties, for example:

if (listBox1.SelectedItems.Count > 0)
   ...
+6
source

Just use the following code to display the selected item from the list - for a WinForm application ...

string s = listbox1.Text;// listbox1

+1

Try the SelectedItems property.

foreach (var selectedItem in listBox1.SelectedItems)
{
    ...
}
0
source

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

// get the first selected item, cast it to MyClass
MyClass item = listBox.SelectedItems[0] as MyClass;
if (item != null)
{
    // use item here
}
0
source

Source: https://habr.com/ru/post/1748221/


All Articles