【问题标题】:How prevent duplicate items listView C#如何防止重复项目listView C#
【发布时间】:2013-02-23 19:23:01
【问题描述】:

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

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

我需要防止重复项但无法正常工作,我该如何解决?

【问题讨论】:

  • Contains 检查 reference 是否存在,而不是具有相同 .Text 和(可能)类似子项的“相似”项。

标签: c# listview duplicates


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      这段代码对我有用:

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

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

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

        【讨论】:

          【解决方案5】:
          String csVal = Value;
          ListViewItem csItem = new ListViewItem(csVal);
          if (!listViewABC.Items.ContainsKey(csVal))
          {
              csItem.Name = csVal;
              listViewABC.Items.Add(csItem );
          }
          

          【讨论】:

            猜你喜欢
            • 2019-04-12
            • 1970-01-01
            • 2019-06-20
            • 1970-01-01
            • 2016-05-13
            • 1970-01-01
            • 2020-05-14
            • 2019-10-12
            • 2023-03-27
            相关资源
            最近更新 更多