Skip to content

How to check for duplication in listview?

shah

Asked May 3, 2007, 6:15 AM EDT2 answers
Share
LinkedInX
I have the code which i used to check duplication in listbox but not working?

Q. I have 3 columns in listview grid and i want to check duplication with only one field. How to do that?

if(listView1.Items.Contains(lvi) == false)
{
//Add the item to the ListView Control
listView1.Items.Add(lvi);
}
else
{
//Warn user of duplicate entry...
MessageBox.Show("Duplicate Item!");
}

2 Answers

Know the answer? Post it. Somebody with the same question will find it here.

  • Mike Gold
    0
    I have the code which i used to check duplication in listbox but not working?

    Q. I have 3 columns in listview grid and i want to check duplication with only one field. How to do that?

    if(listView1.Items.Contains(lvi) == false)
    {
    //Add the item to the ListView Control
    listView1.Items.Add(lvi);
    }
    else
    {
    //Warn user of duplicate entry...
    MessageBox.Show("Duplicate Item!");
    ----

    This will not work because you are probably not passing the exact same object, but an object that contains the same text.  Is this the situation?

    For example this works fine with your code:

    ListViewItem lvi = new ListViewItem("dog");
    Add(lvi);
    Add(lvi);

    The second time you try to add the same object, you get the message box.

    If you want to check the internal information in the row against your Add, you can compare a key in your item.  The key corresponds to the name of the item:

    if (!listView1.Items.ContainsKey(lvi.Name))
    {
     //Add the item to the ListView Control
     listView1.Items.Add(lvi);
    }
    else
    {
    //Warn user of duplicate entry...
    MessageBox.Show("Duplicate Item!");
    }


    This will work for the following code with a unique name for your ListViewItem (the unique name being "item1":

    ListViewItem lvi1 = new ListViewItem("dog");
    lvi1.Name = "item1";
    Add(lvi1);

    Otherwise you'll need to compare the list of items for each subitem:

    C#
    private bool IsInCollection(ListViewItem lvi)
     {
       foreach (ListViewItem item in listView1.Items)
       {
             bool subItemEqualFlag = true;
             for (int i = 0; i < item.SubItems.Count; i++)
                {
                     string sub1 = item.SubItems[i].Text;
                     string sub2 = lvi.SubItems[i].Text;
                     if (sub1 != sub2)
                      {
                         subItemEqualFlag = false;
                      }
                 }
                if (subItemEqualFlag)
                                return true;
         }
         return false;
    }
    0
  • 0
    thanks a million Mike. Thanks a lot It worked.
    0