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:

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!");
}

Answer:
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 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!");
}

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, if you don't provide a key, you'll need to compare the list of items and check each subitem within each item:

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;

}

转载于:https://www.cnblogs.com/PocketZ/archive/2011/07/31/2122648.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值