CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Dec 2010
    Posts
    8

    Copying listview row without duplication

    Hi,

    Trying to copy a ListView row to another listView control and to prevent having duplicates I'm checking if the item already exists first.
    If the row doesn't exist then copy it if not don't do anything.
    My code doesn't seem to work and thinks the row does't exist all the time.
    could someone tell me where I am going wrong?
    Thanks and advance.

    private void CopyChecked ( ListView sourceListView, ListView destListView )
    {
    foreach ( ListViewItem item in sourceListView.Items )
    if (item.Checked)
    {
    if (CheckIfListViewItemExistsInListView(item,destListView)==false)
    {
    destListView.Items.Add(item.Clone() as ListViewItem);
    }
    }
    }



    ------------------------
    private bool CheckIfListViewItemExistsInListView(ListViewItem itemToAdd, ListView destListView)
    {
    bool exists = false;
    foreach (ListViewItem item in destListView.Items)
    {
    if(item == itemToAdd)
    {
    exists=true;
    break; // Break the loop if the item found.
    }
    }
    return exists;

    }
    Last edited by walidm38; January 12th, 2011 at 08:50 AM.

  2. #2
    Join Date
    Jun 2008
    Posts
    2,477

    Re: Copying listview row without duplication

    Well, this is obviously why:

    Code:
    destListView.Items.Add(item.Clone() as ListViewItem);
    You are cloning the object, i.e., making a deep copy. When you check for equality (BTW, just use if( listview.Items.Contains( item ) ). There is no need to write your own method here) you are checking for reference equality, i.e., do these two references point to the same object. When you clone an object you are making a new object entirely, so the two references no longer point to the same thing.

    You should probably just not close the object. If you need to clone it then you can create your own class that inherits from ListViewItem and override the .Equals method to compare values instead of references. I would probably implement my own IComparable for this situation because people won't expect reference types to be compared by value.

  3. #3
    Join Date
    Jul 2010
    Posts
    82

    Re: Copying listview row without duplication

    item.Clone() and then you're asking why its duplicated?? Thats what Cloning does. Why not copy the row as strings??

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured