tags:

views:

2450

answers:

3

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?

+3  A: 

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.

Neil Barnwell
thanks! I forgot to override equals and hashcode...shame on me.
jjnguy
Did it work? Someone further down said that IndexOf checks the reference, which means that my solution wouldn't work.
Neil Barnwell
The solution fixed it. I just overrode equals and like magic it was fixed.
jjnguy
Okay - be aware that the recommendation is that you always implement GetHashCode and Equals together, in case the object is used in a hashmap.
Neil Barnwell
Yup, thanks for the advice.
jjnguy
+3  A: 

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.

Kon
A: 

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.

Will
It seems to work with just overriding equals correctly.
jjnguy
But Linq is SO MUCH COOLER OMG LOL
Will