IndexOf

J

Joel Lyons

Is it just my imagination, or does ListView.Items.IndexOf not work? I
expected it to work like most collections by finding the item you're looking
for using the items' Equals methods. I created a class derived from
ListViewItem and declared an override for Equals (based on a unique ID
integer). If I fill my ListView with some of these items and try to find
one of them using IndexOf, it never succeeds. If I copy the Items
collection into an ArrayList and use IndexOf on that, it works! (I tried
wrapping the collection using ArrayList.Adapter instead, but that also
fails).

m_listView.Items.Add(new MyListViewItem(1));
m_listView.Items.Add(new MyListViewItem(2));

m_listView.Items.Add(new MyListViewItem(3));
//this always returns -1
int n1 = m_listView.Items.IndexOf(new MyListViewItem(2));
//this always finds it at index 2!
ArrayList items = new ArrayList(m_listView.Items);
int n2 = items.IndexOf(new MyListViewItem(2));


Is anyone else seeing this or am I smoking something???
-Joel
 
J

Jon Skeet [C# MVP]

Joel Lyons said:
Is it just my imagination, or does ListView.Items.IndexOf not work? I
expected it to work like most collections by finding the item you're looking
for using the items' Equals methods. I created a class derived from
ListViewItem and declared an override for Equals (based on a unique ID
integer). If I fill my ListView with some of these items and try to find
one of them using IndexOf, it never succeeds. If I copy the Items
collection into an ArrayList and use IndexOf on that, it works! (I tried
wrapping the collection using ArrayList.Adapter instead, but that also
fails).

m_listView.Items.Add(new MyListViewItem(1));
m_listView.Items.Add(new MyListViewItem(2));

m_listView.Items.Add(new MyListViewItem(3));
//this always returns -1
int n1 = m_listView.Items.IndexOf(new MyListViewItem(2));
//this always finds it at index 2!
ArrayList items = new ArrayList(m_listView.Items);
int n2 = items.IndexOf(new MyListViewItem(2));


Is anyone else seeing this or am I smoking something???

No, I believe ListViewItemCollection.IndexOf just checks for identity,
not equality.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top