James James - 11 days ago 6
Vb.net Question

Adding item into listview1 and remove if the item has already in the listview1 or replace

I have

listview1
with 2 columns. I already have a code for adding items but my problem is when I add again the same item in
listview1
, it shows duplicates and when I continue to add the same item, the items in listview are increasing with same data.

Example for what I need:

When
listview1
has already a data in 1st column = 1 and in 2nd column = A, and I want to add again with a data like these 1st column = 1 and in 2nd column = B. I have 2 solutions and I try to code it but with no luck. My 2 solutions is these:


  1. I just want to update only the data in 2nd column, from "A" to "B" but with the same 1st column data and no additional item will be added into listview like nothing just update/replace it.



OR


  1. Remove the item that will cause duplication and add the same item so there will be no duplicates.



Here's my code for adding item:

Private Sub rbChoiceA_Checked(ByVal sender As Object, ByVal e As EventArgs)

Dim rbA As RadioButton = TryCast(sender, RadioButton)
Dim str As String = rbA.Parent.Name
str = str.Remove(0, 6)
lab1.Text = str
Dim item As ListViewItem
Dim row As String() = New String(2) {}
row(0) = str
row(1) = rbA.Text
item = New ListViewItem(row)
ListView1.Items.Add(item)

End Sub


I just need help to add the code for my problem. Your answers is highly appreciated. Thanks in advance!

Answer

Find the item before add it

If (ListView1.FindItemWithText(row(0)) Is Nothing) Then
    ListView1.Items.Add(item)
End If