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:
- 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);
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:
- 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!");
- }
- ListViewItem lvi1 = new ListViewItem("dog");
- lvi1.Name ="item1";
- Add(lvi1);
- 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;
- }


Prashant MorePosted Dec 9, 2007, 3:00 AM EST
Sir, How to join tables from diffrent servers?
Prashant MorePosted Dec 9, 2007, 2:58 AM EST
Sir, How to delete rows which are duplicate?