How Can I Get the Index of An Item in a ListBox?

2019-04-11 20:04发布

问题:

I am adding items to a ListBox like so:

myListBox.Items.addRange(myObjectArray);

and I also want to select some of the items I add by the following:

foreach(MyObject m in otherListOfMyObjects) 
{
    int index = myListBox.Items.IndexOf(m);
    myListBox.SelectedIndices.Add(index);
}

however index is always -1.

Is there a different way to get the index of an object in a ListBox?

回答1:

You should make sure that MyObject overrides Equals(), GetHashCode() and ToString() so that the IndexOf() method can find the object properly.

Technically, ToString() doesn't need to be overridden for equality testing, but it is useful for debugging.



回答2:

You can use some kind of a key for values in the listbox, like GUIDs. Then you can easily use myListBox.Items.FindByValue(value) to find the right item.



回答3:

IndexOf checks the reference, so if the items in otherListOfMyObjects don't reference the same exact objects in memory as myListBox.Items, then IndexOf won't work.

What you could do is use linq. Here's some pseudocode that looks like C#, may compile and may actually work:

var items =  from x in myListBox.Items where otherListOfMyObjects.Any(y => y == x /*SEE NOTE*/) select x;
foreach(item i in items)
  myListBox.SelectedItems.Add(i);

Obviously, that won't work as y==x will always return false (that's why your current method won't work). You need to substitute y==x to perform an equality comparison that will determine equality as YOU define it for MyObject. You can do this by adding an ID as Fallen suggested or by overriding a buttload of methods as Neil suggested (+s for both of them), or by just determining which properties of MyObject to check in order to identify them as exactly the same object.



标签: c# listbox