开发者

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 = li开发者_如何学JAVAstBox.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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜