列表视图中的重复条目

时间:2014-02-18 19:22:56

标签: c# listview duplicates

嗯...对不起,任何人都可以提供帮助......我正在尝试比较列表视图中是否已经存在的项目,但首先当我添加项目时,它没关系。但是当我更改项目然后添加项目它仍然说重复条目。我想要做的是每当我添加一个项目时,它将检测项目是否已经在列表视图中。在此先感谢!!

while (myReadersup1.Read())
        {
            string item = myReadersup1.GetString("ProdName");
            string price = myReadersup1.GetFloat("ProdPrice").ToString("n2");
            string noi = cmbNOI.SelectedItem.ToString();
            bool alreadyInList = false;

                foreach (ListViewItem itm in lvCart.Items)
                {

                    if (lvCart.Items.Cast<object>().Contains(itm))
                    {
                        alreadyInList = true;
                        MessageBox.Show("Duplicate Entry!");
                        break;

                    }

                }
                if (!alreadyInList)
                {
                    lvCart.Items.Add(new ListViewItem(new string[] { item, price, noi }));
                }                                                

2 个答案:

答案 0 :(得分:0)

在你的foreach循环中,如果找不到该项,则需要一个将alreadyInList设置为false的else。否则,它总是如此。

答案 1 :(得分:0)

当您浏览当前项目时,您正在检查它是否在项目集合中,并且始终为真。您可能希望将其更改为类似的内容:

    private bool AddListViewItem(string item, string price, string noi)
    {
        if (this.DetectDuplicate(item, price, noi))
            return false;

        string[] content = new string[] { item, price, noi };
        ListViewItem newItem = new ListViewItem();
        newItem.Content = content;
        _listView.Items.Add(newItem);
        return true;
    }

    private bool DetectDuplicate(string item, string price, string noi)
    {
        foreach (ListViewItem lvwItem in _listView.Items)
        {
            string[] itemContent = lvwItem.Content as string[];
            Debug.Assert(itemContent != null);
            if (itemContent[0].Equals(item) &&
                itemContent[1].Equals(price) &&
                itemContent[2].Equals(noi))
                return true;
        }

        return false;
    }