Getting Selected Items From WinForm ListBox?

2019-06-28 04:15发布

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?

4条回答
时光不老,我们不散
2楼-- · 2019-06-28 04:28

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)
   ...
查看更多
看我几分像从前
3楼-- · 2019-06-28 04:28

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
}
查看更多
Juvenile、少年°
4楼-- · 2019-06-28 04:33

Try the SelectedItems property.

foreach (var selectedItem in listBox1.SelectedItems)
{
    ...
}
查看更多
倾城 Initia
5楼-- · 2019-06-28 04:41

Just use the following code to display the selected item from the listbox - for WinForm app...

string s = listbox1.Text; //replace listbox1 with your listbox control

查看更多
登录 后发表回答