How prevent duplicate items listView C#

笑着哭i 提交于 2019-11-28 03:54:43

问题


I am using Windows Forms. With this code I add items to listView from 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?


回答1:


You should be using ContainsKey(string key) instead of 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);
}



回答2:


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

  • Contains On Items collection, and
  • FindItemWithText methods

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



回答3:


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



回答4:


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.

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




回答5:


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


来源:https://stackoverflow.com/questions/15290779/how-prevent-duplicate-items-listview-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!