使用C#阻止ListView中的双重条目?

我们如何访问添加到ListView的项目?

我要做的是:在列表视图中添加一个项目。 我想检查要添加到列表视图的项目是否已存在于ListView中。

我正在使用C#和Visual Studio 2005。

ListView类提供了一些不同的方法来确定项是否存在:

  • Items集合上使用Contains
  • 使用FindItemWithText方法之一

它们可以按以下方式使用:

 // assuming you had a pre-existing item ListViewItem item = ListView1.FindItemWithText("test"); if (!ListView1.Items.Contains(item)) { // doesn't exist, add it } // or you could find it by the item's text value ListViewItem item = ListView1.FindItemWithText("test"); if (item != null) { // it exists } else { // doesn't exist } // you can also use the overloaded method to match sub items ListViewItem item = ListView1.FindItemWithText("world", true, 0); 

只需添加您的项目,并确保您指定一个名称。 然后只需使用Items集合的ContainsKey方法来确定它是否存在,就像这样。

 for (int i = 0; i < 20; i++) { ListViewItem item = new ListViewItem("Item" + i.ToString("00")); item.Name = "Item"+ i.ToString("00"); listView1.Items.Add(item); } MessageBox.Show(listView1.Items.ContainsKey("Item00").ToString()); // True MessageBox.Show(listView1.Items.ContainsKey("Item20").ToString()); // False 

你可以这样做:

  ListViewItem itemToAdd; bool exists = false; foreach (ListViewItem item in yourListView.Items) { if(item == itemToAdd) exists=true; } if(!exists) yourListView.Items.Add(itemToAdd); 

添加后,以下内容将有助于在ListView控件中找到ListViewItem

 string key = ; if (!theListViewControl.Items.ContainsKey(key)) { item = theListViewControl.Items.Add(key, "initial text", -1); } // now we get the list item based on the key, since we already // added it if it does not exist item = theListViewControl.Items[key]; ... 

注意用于将项添加到ListView项集合的键可以是任何唯一值,可以标识项集合中的ListViewItem 。 例如,它可以是哈希码值或附加到ListViewItem的对象上的某个属性。

罗伯答案的一个小修正

  ListViewItem itemToAdd; bool exists = false; foreach (ListViewItem item in yourListView.Items) { if(item == itemToAdd) { exists=true; break; // Break the loop if the item found. } } if(!exists) { yourListView.Items.Add(itemToAdd); } else { MessageBox.Show("This item already exists"); } 

对于多列ListView,您可以使用以下代码来防止根据任何列重复输入:

让我们假设有一个这样的阶级法官

 public class Judge { public string judgename; public bool judgement; public string sequence; public bool author; public int id; } 

我想在ListView中添加此类的唯一对象。 在这个类中,id是唯一字段,因此我可以在此字段的帮助下检查ListView中的唯一记录。

 Judge judge = new Judge { judgename = comboName.Text, judgement = checkjudgement.Checked, sequence = txtsequence.Text, author = checkauthor.Checked, id = Convert.ToInt32(comboName.SelectedValue) }; ListViewItem lvi = new ListViewItem(judge.judgename); lvi.SubItems.Add(judge.judgement ? "Yes" : "No"); lvi.SubItems.Add(string.IsNullOrEmpty(judge.sequence) ? "" : txtsequence.Text); lvi.SubItems.Add(judge.author ? "Yes" : "No"); lvi.SubItems.Add((judge.id).ToString()); if (listView1.Items.Count != 0) { ListViewItem item = listView1.FindItemWithText(comboName.SelectedValue.ToString(), true, 0); if (item != null) { // it exists } else { // doesn't exist } }