我正在使用Windows Forms。使用此代码,我将项目从listView添加到comboBox中。

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

我需要防止重复的物品但不能使用,我该如何解决?

最佳答案

您应该使用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);
}

09-27 09:12