Instance Hunter
Instance Hunter

Reputation: 7925

What could cause listBox.Items.Remove to remove the wrong item?

Crap. I found the problem. Never mind. When the item was removed, it was supposed to be replaced with another item, but before the replacing could happen, an event was triggered that removed the wrong item since the replacing had not yet taken place.

Both ways, the assertions fail:

var item4 = listBox.Items[4];
var item5 = listBox.Items[5];

listBox.Items.Remove(item5);

Debug.Assert(listBox.Items.Contains(item4), "item4 not found");
Debug.Assert(!listBox.Items.Contains(item5), "item5 still found");

And:

var item4 = listBox.Items[4];
var item5 = listBox.Items[5];

listBox.Items.RemoveAt(5);

Debug.Assert(listBox.Items.Contains(item4), "item4 not found");
Debug.Assert(!listBox.Items.Contains(item5), "item5 still found");

ListBox items are custom classes. ListBox is owner drawn.

The assertion item4 != item5 passes.

Upvotes: 1

Views: 328

Answers (2)

Doug Chamberlain
Doug Chamberlain

Reputation: 11341

When you remove an item from a listbox the listbox is reindexed. Item [6] becomes item [5].

http://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.objectcollection.remove(VS.71).aspx

Upvotes: 0

Jorge Córdoba
Jorge Córdoba

Reputation: 52123

ListBox items are custom classes.

If you've overriden GetHashCode and Equals method then Remove might find that item4 and item5 are indeed the same and thus remove item4 instead of item5 because that's the first one it finds.

Try doing it twice. If both items are removed then that's most likely the case. Also try asserting item4.Equals(item5) instead of item4 == item5.

Upvotes: 2

Related Questions