Getting Selected Items From WinForm ListBox?

纵然是瞬间 提交于 2019-12-05 17:53:14

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

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

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
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!