简体   繁体   English

从 WinForm ListBox 中获取所选项目?

[英]Getting Selected Items From WinForm ListBox?

I have a ListBox in a WinForm with multiselect enabled.我在启用多选的 WinForm 中有一个 ListBox。

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.因为这是一个较旧的非泛型集合,所以最好不要使用var来声明 item 变量。 That would only get you a reference of type object .那只会给你一个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.试试 SelectedItems 属性。

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

The selected items are found in the SelectedItems property.所选项目位于SelectedItems属性中。 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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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