如何防止重复项目listView C#
我正在使用如何防止重复项目listView C#,c#,listview,duplicates,C#,Listview,Duplicates,我正在使用Windows窗体。使用此代码,我可以从组合框向列表视图添加项目 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.
Windows窗体
。使用此代码,我可以从组合框向列表视图添加项目
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);
}
我需要防止重复项但不起作用,如何解决此问题?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);
我只是在猜测文本属性,但我很确定这是真的
或者-只需拥有一个
列表
,并将其用作列表的数据源。您应该使用ContainsKey(字符串键)
而不是Contains(ListViewItem)
这个代码对我有用:
if(DialogResult.OK == fileDialogue.ShowDialog())
{
foreach (var v in fileDialogue.FileNames)
{
if (listView.FindItemWithText(v) == null)
{
listView.Items.Add(v);
}
else
//Throw error message
包含
检查引用是否存在,而不是具有相同.Text
和(可能)类似子项的“类似”项。
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);
}
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 );
}