How can I get the index of an item in a ListBox?

I add elements to ListBoxas follows:

myListBox.Items.addRange(myObjectArray);

and I also want to select some of the elements that I add as follows:

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

however indexalways -1.

Is there any other way to get the index of an object in ListBox?

+3
source share
3 answers

You need to make sure that it MyObjectoverrides Equals(), GetHashCode()and ToString()so that the method IndexOf()can correctly find the object.

Technically, you ToString()do not need to override it for equality testing, but it is useful for debugging.

+8
source

- , GUID. myListBox.Items.FindByValue(value), .

+7

IndexOf , , ListOfMyObjects , myListBox.Items, IndexOf .

, linq. , #, :

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 this will not work, since y == x will always return false (so your current method will not work). You need to substitute y == x to perform an equality comparison, which will determine the equality as you define it for MyObject. You can do this by adding the identifier suggested by Fallen, or by overriding the methods suggested by Neal (+ s for both of them), or simply by defining which properties of MyObject need to be checked to identify them as exactly the same object.

0
source

All Articles