6

私はを使用してWindows Formsいます。このコードを使用して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);
}

アイテムの重複を防ぐ必要がありますが、機能しません。どうすればこれを解決できますか?

4

5 に答える 5

12

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);
于 2013-03-08T09:42:14.313 に答える
8

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);
}
于 2013-03-08T09:43:23.693 に答える
2

このコードは私のために働いた:

if(DialogResult.OK == fileDialogue.ShowDialog())
            {
                foreach (var v in fileDialogue.FileNames)
                {
                    if (listView.FindItemWithText(v) == null)
                    {
                        listView.Items.Add(v);
                    }

                    else
                    //Throw error message
于 2013-12-03T05:56:40.807 に答える
0
if (!listView1.Items.Any(i => i.text == lvi.text))
{
    listView1.items.Add(lvi)
}

textプロパティを推測しているだけですが、そこにあると確信しています。

または、を持ってList<string>、リストのデータソースとして使用します。

于 2013-03-08T09:43:11.043 に答える
0
String csVal = Value;
ListViewItem csItem = new ListViewItem(csVal);
if (!listViewABC.Items.ContainsKey(csVal))
{
    csItem.Name = csVal;
    listViewABC.Items.Add(csItem );
}
于 2015-01-16T05:13:28.250 に答える