How do I Check for Duplicate Items in a ListView

This How To was written in response to the following question in the C# Corner Forums about ListViews:
The user states: 
Question:  "I have code which I used to check duplication in a ListView,  but it doesn't seem to be working.  Here is my situation.  I have three columns in a ListView and I want to check to make sure that I don't duplicate a field when I add an item to the ListView. How do I do that?"
I tried this code, but it doesn't seem to work:
  1. if  (listView1.Items.Contains(lvi) == false)  
  2. {  
  3. //Add the item to the ListView Control  
  4. listView1.Items.Add(lvi);  
  5. }  
  6. else  
  7. {  
  8.   //Warn user of duplicate entry...  
  9.  MessageBox.Show("Duplicate Item!");  
  10. }  
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:
  1. ListViewItem lvi = new ListViewItem("dog");  
  2. Add(lvi);  
  3. 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 provide a key in your item.  The key corresponds to the name of the item and can be used to compare items using the ContainsKey method:
  1. if (!listView1.Items.ContainsKey(lvi.Name))  
  2. {  
  3.    //Add the item to the ListView Control  
  4.    listView1.Items.Add(lvi);  
  5. }  
  6. else  
  7. {  
  8.   //Warn user of duplicate entry...  
  9.  MessageBox.Show("Duplicate Item!");  
  10. }  
This will work for the following code with a unique name for your ListViewItem (the unique name being "item1"):
  1. ListViewItem lvi1 = new ListViewItem("dog");  
  2. lvi1.Name ="item1";  
  3. Add(lvi1);  
Otherwise, if you don't provide a key,  you'll need to compare the list of items and check each subitem  within each item: 
  1. private bool IsInCollection(ListViewItem lvi)  
  2.  {  
  3.    foreach (ListViewItem item in listView1.Items)  
  4.    {  
  5.          bool subItemEqualFlag = true;  
  6.          for (int i = 0; i < item.SubItems.Count; i++)  
  7.             {  
  8.                  string sub1 = item.SubItems[i].Text;  
  9.                  string sub2 = lvi.SubItems[i].Text;  
  10.                  if (sub1 != sub2)  
  11.                   {  
  12.                      subItemEqualFlag =false;  
  13.                   }  
  14.              }  
  15.             if (subItemEqualFlag)  
  16.                             return true;  
  17.      }  
  18.      return false;  
  19. } 

Similar Articles