简体   繁体   中英

Getting Selected Items From WinForm ListBox?

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?

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)
   ...

只需使用以下代码从ListBox显示所选项目 - 对于 WinForm 应用程序...

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

Try the SelectedItems property.

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

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM