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?
You should make sure that
MyObjectoverridesEquals(),GetHashCode()andToString()so that theIndexOf()method can find the object properly.Technically,
ToString()doesn’t need to be overridden for equality testing, but it is useful for debugging.