如何防止重复项 listView C#

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15290779/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 16:18:16  来源:igfitidea点击:

How prevent duplicate items listView C#

c#listviewduplicates

提问by Vincenzo Lo Palo

I am using Windows Forms. With this code I add items to listViewfrom comboBox.

我正在使用Windows Forms. 使用此代码,我将项目添加到listViewfrom 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);
}

I need prevent duplicate items but not work, How Can I solve this?

我需要防止重复项目但不起作用,我该如何解决?

采纳答案by Larry

You should be using ContainsKey(string key)instead of Contains(ListViewItem item)

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

回答by Parimal Raj

The ListView class provides a few way to check if an item exists:

ListView 类提供了几种检查项目是否存在的方法:

It can be used like :

它可以像这样使用:

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

回答by PhonicUK

if (!listView1.Items.Any(i => i.text == lvi.text))
{
    listView1.items.Add(lvi)
}

I'm just guessing on the text property, but I'm pretty sure that's there.

我只是在猜测 text 属性,但我很确定它就在那里。

Alternatively - just have a List<string>and use it as a data source for your list.

或者 - 只需拥有一个List<string>并将其用作列表的数据源。

回答by codegasm

This code worked for me:

这段代码对我有用:

if(DialogResult.OK == fileDialogue.ShowDialog())
            {
                foreach (var v in fileDialogue.FileNames)
                {
                    if (listView.FindItemWithText(v) == null)
                    {
                        listView.Items.Add(v);
                    }

                    else
                    //Throw error message

回答by sgupta

String csVal = Value;
ListViewItem csItem = new ListViewItem(csVal);
if (!listViewABC.Items.ContainsKey(csVal))
{
    csItem.Name = csVal;
    listViewABC.Items.Add(csItem );
}