简体   繁体   中英

How do I get Index from listboxitem by its content?

Is there a way to get a Listbox Item Index by its content? Something like:

id = listbox.Items.Contains("text");

I know that this way I'll get a bool result, but I don't know how to get the item Index. If I could get the Index I could be able to remove items with

listbox.Items.RemoveAt(id);

In WPF

ListBox listBox = new ListBox();   
int index = listBox.Items.IndexOf(item);

Look for the item's index, and then you can remove it with the given method:

int index = myListBox.Items.IndexOf(itemToSearch); 
/*if there is no coincidence, it returns -1, so you must check for that return, else RemoveAt(-1) would give you a runtime error.*/
if (index >=0)
{
myListBox.Items.RemoveAt(index);
}

Assuming the item is not selected but for some reason you just want to find it in the list:

The listbox.items is a listbox object collection: So:

id=listbox.items.IndexOf("text");

will do the trick.

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