如何获取ListBox中的项目索引?

jjn*_*guy 3 c# listbox

我正在添加项目,ListBox所以:

myListBox.Items.addRange(myObjectArray);
Run Code Online (Sandbox Code Playgroud)

我还想选择以下添加的一些项目:

foreach(MyObject m in otherListOfMyObjects) 
{
    int index = myListBox.Items.IndexOf(m);
    myListBox.SelectedIndices.Add(index);
}
Run Code Online (Sandbox Code Playgroud)

index总是如此-1.

是否有不同的方法来获取对象的索引ListBox

Nei*_*ell 8

你应该确保MyObject覆盖Equals(),GetHashCode()并且ToString()使该IndexOf()方法能够正确地找到对象.

从技术上讲,ToString()不需要重写相等性测试,但它对调试很有用.


Kon*_*Kon 7

您可以在列表框中使用某种键作为值,例如GUID.然后,您可以轻松地使用myListBox.Items.FindByValue(value)找到正确的项目.