如何防止重复项目listView C#
问题描述:
我正在使用Windows Forms
。通过此代码,我可以从comboBox
向listView
添加项目。如何防止重复项目listView C#
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);
}
+0
工程像魅力!谢谢! – 2013-03-08 09:53:28
+0
两者都不起作用 – CodeOptimizer 2016-09-21 13:35:42
答
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);
答
if (!listView1.Items.Any(i => i.text == lvi.text))
{
listView1.items.Add(lvi)
}
我只是猜测文本属性,但我很确定那里。
或者 - 只需要一个List<string>
并将其用作列表的数据源。
答
此代码为我工作:
if(DialogResult.OK == fileDialogue.ShowDialog())
{
foreach (var v in fileDialogue.FileNames)
{
if (listView.FindItemWithText(v) == null)
{
listView.Items.Add(v);
}
else
//Throw error message
答
String csVal = Value;
ListViewItem csItem = new ListViewItem(csVal);
if (!listViewABC.Items.ContainsKey(csVal))
{
csItem.Name = csVal;
listViewABC.Items.Add(csItem);
}
的'Contains'检查是否* *参考存在,而不是一个“类似“项目具有相同的'.Text'和(也许)类似的子项目。 – 2013-03-08 09:41:08