jjnguy
jjnguy

Reputation: 138972

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

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?

Upvotes: 3

Views: 25679

Answers (3)

user1228
user1228

Reputation:

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.

Upvotes: 0

Kon
Kon

Reputation: 27451

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.

Upvotes: 7

Neil Barnwell
Neil Barnwell

Reputation: 42165

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.

Upvotes: 8

Related Questions