You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何使用ContainsKey无法阻止ListView插入重复项?

Troubleshooting Your ListView Duplicate Check Issue

Hey there! I’ve run into this exact problem before, so let’s break down why your code isn’t catching duplicates even though it works for others. The root cause almost always boils down to a tiny detail you might have missed in how ContainsKey interacts with ListViewItems.

The Main Culprit: Missing Name Property Assignment

Here’s the key thing: ListView.Items.ContainsKey() doesn’t check the Text of your ListViewItem—it checks the Name property. In your current code, you’re creating the ListViewItem with the brand text, but you never set its Name to match that text.

When you add an item without setting Name, .NET automatically generates a unique, generic name for it (like "ListViewItem1", "ListViewItem2", etc.), so ContainsKey(txtBrand.Text.Trim()) will never find a match—even if the Text is identical to an existing item. The person whose code works probably has that missing line in their implementation without mentioning it!

Fixing the Code

Here’s your revised code with the critical fix, plus some robustness improvements:

string brandName = txtBrand.Text.Trim();

// First, validate empty input
if (string.IsNullOrEmpty(brandName))
{
    MessageBox.Show("Please enter a brand name!");
    return;
}

// Check for duplicates (now that we'll set the Name property correctly)
if (listView1.Items.ContainsKey(brandName))
{
    MessageBox.Show("This brand is already added!");
}
else
{
    ListViewItem newItem = new ListViewItem(brandName);
    newItem.Name = brandName; // This line was missing! It's what ContainsKey looks for
    listView1.Items.Add(newItem);
    txtBrand.Text = string.Empty;
}

Other Possible Edge Cases to Check

If the above fix doesn’t solve it right away, consider these scenarios:

  • Case sensitivity: ContainsKey() is case-sensitive. If you want to treat "Apple" and "apple" as duplicates, normalize the text first (e.g., convert to lowercase) before checking and setting the Name:
    string normalizedBrand = brandName.ToLowerInvariant();
    if (listView1.Items.ContainsKey(normalizedBrand))
    {
        MessageBox.Show("This brand is already added!");
    }
    else
    {
        ListViewItem newItem = new ListViewItem(brandName);
        newItem.Name = normalizedBrand;
        listView1.Items.Add(newItem);
    }
    
  • Hidden whitespace: Double-check that your Trim() is handling all whitespace correctly. You could add a debug line to verify the cleaned input: Console.WriteLine($"Cleaned brand: '{brandName}'");

内容的提问来源于stack exchange,提问作者Mr. Benbenbenbenben

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:19:05