views:

235

answers:

1

Hi everyone,

I'm copying ListViewItems from one ListView to another, sth. like:

foreach (ListViewItem item in usersListView.SelectedItems) {
    selectedUsersListView.Items.Add((ListViewItem)item.Clone());
}

If I want to use ListView.ItemCollection.Contains() to determine if an item was already copied I always get false:

foreach (ListViewItem item in usersListView.SelectedItems) {
    if (!selectedUsersListView.Items.Contains(item) { // always !false
        selectedUsersListView.Items.Add((ListViewItem)item.Clone());
    }
}

I did the following to solve my problem:

foreach (ListViewItem item in usersListView.SelectedItems) {
    ListViewItem newItem = (ListViewItem)item.Clone();
    newItem.Name         = newItem.Text;

    if (!selectedUsersListView.Items.ContainsKey(newItem.Name) { // this works
        selectedUsersListView.Items.Add(newItem);
    }
}

So, it's ok that this solves my problem but I still have no idea why ListView.ItemCollection.Contains() doesn't work...

How does ListView.ItemCollection.Contains() identify if an item already exists?

How do ListViewItems have to be initialised that ListView.ItemCollection.Contains() (not ListView.ItemCollection.ContainsKey()) is able to identify them?

+3  A: 

Internally ListViewItemCollection uses the == operator to test for equality. Since ListViewItem does not override the == operator, ListViewItemCollection.Contains compares references. Since you are cloning your ListViewItems, your call to Contains will always return false because you are comparing two different object references.

Edit:

You cannot add the same ListViewItem to two different ListViews so what you are trying to do is not possible using Contains. You need to use ContainsKey. In the following example Contains will return true:

var item = new ListViewItemEquality("Item1");
listView1.Items.Add(item1);
Debug.Assert(listView1.Items.Contains(item1));
Jakob Christensen
Then I can't really imagine a case where .Contains() will return true... could you please post a short example?
Inno
I edited my post to show an example.
Jakob Christensen