2014-02-18 68 views
0

嗯...不好意思,任何人都可以幫忙...我想比較一下,如果項目已經存在於listview中,但是首先當我添加一個項目時沒關係。但是,當我改變項目,然後添加它仍然表示重複條目的項目。我想要做的是每當我添加一個項目時,它會檢測項目是否已經在列表視圖中。提前致謝!!列表視圖中的重複條目

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 })); 
       }             

回答

0

在你的foreach循環中,如果沒有找到該項目,你需要一個else設置alreadyInList爲false。否則,它總是如此。

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; 
    }