如何防止重复项listView C#

Vin*_*alo 6 c# listview duplicates

我在用Windows Forms.有了这个代码,我添加项目listViewcomboBox.

ListViewItem lvi = new ListViewItem();
lvi.Text = comboBox1.Text;
lvi.SubItems.Add("");
lvi.SubItems.Add("");
lvi.SubItems.Add("");
lvi.SubItems.Add("")

if (!listView1.Items.Contains(lvi))
{
    listView1.Items.Add(lvi);
}
Run Code Online (Sandbox Code Playgroud)

我需要防止重复的项目,但不能工作,我该如何解决这个问题?

PaR*_*RaJ 11

ListView类提供了一些检查项是否存在的方法:

它可以像:

// assuming you had a pre-existing item
ListViewItem item = ListView1.FindItemWithText("item_key");
if (item == null)
{
    // item does not exist
}


// you can also use the overloaded method to match subitems
ListViewItem item = ListView1.FindItemWithText("sub_item_text", true, 0);
Run Code Online (Sandbox Code Playgroud)


Lar*_*rry 8

你应该使用ContainsKey(string key)而不是Contains(ListViewItem item)

var txt = comboBox1.Text;

if (!listView1.Items.ContainsKey(txt))
{
    lvi.Text = txt;

    // this is the key that ContainsKey uses. you might want to use the value 
    // of the ComboBox or something else, depending the combobox is freetext 
    // or regarding your scenario.
    lvi.Name = txt;

    lvi.SubItems.Add("");
    lvi.SubItems.Add("");
    lvi.SubItems.Add("");
    lvi.SubItems.Add("");

    listView1.Items.Add(lvi);
}
Run Code Online (Sandbox Code Playgroud)