Check if list view contain item

i have a listview with 3 columns (id , name, author), i use this method to add row:

     public void addToLv(Book book)
    {

        //TODO: Verifier si l'item existe avant d'ajouter
        ListViewItem lvi1 = new ListViewItem(book.id.ToString());
        lvi1.Text = book.id.ToString();
        lvi1.SubItems.Add(book.name);
        lvi1.SubItems.Add(carte.author);

        listView1.Items.Add(lvi1);

    }

Now i wan’t to check if book exists before i insert the new one to avoid duplicate element, i try this code but it’S not working i have use this line but it’s not working:

  (listView1.Items.ContainsKey(book.id))
         {
      listView1.Items.Add(lvi1);
         }

Can you help me please? thank you

Answer

I think you missed a “!” (not) in your code.

(!listView1.Items.ContainsKey(book.id))
     {
  listView1.Items.Add(lvi1);
     }

Your code is saying that if your listview contains that key, you will add another entry that has that key. But it seems you want to do the opposite, right? If your listview does not contain an entry with that key, you want to add an entry that has that key.

Leave a Reply

Your email address will not be published. Required fields are marked *