Kobina Ebo Yankson
Kobina Ebo Yankson

Reputation: 31

How to update values of an existing Item in a ListView?

I am working on a little project and I have to add an item with some values into a ListView.
I want to be able to update the values of an Item if it is added again and not read the same Item with different details again.

Below is the code I have managed to come up with thus far:

For Each item as ListViewItem in MainListView.Items
    If item.SubItems(0).Text = ItemCode Then
       item.SubItems(3).Text += ItemQty
       item.SubItems(5).Text += ItemPrice
    Else
       ' normal listview insert codes run here
    End If
Next

As it stands now, the values are only able to update if the Item is first on the list but once it moves a step downwards, the similar Item also inserts into the ListView with it's own records instead of finding and updating the already existing one.

Any help to rectify it would be greatly appreciated. Thanks.

Upvotes: 0

Views: 4540

Answers (1)

Mary
Mary

Reputation: 15091

Loop through your ListView checking if the ItemCode exists. If it is found then update the item and exit the sub with the Return statement. It is OK to use the For Each because you are not altering the collection only changing the values of one of the items in the collection. If you were adding or removing an item from the list view you could not use the For Each because the collection itself is being altered.

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    For Each item As ListViewItem In MainListView.Items
        If item.SubItems(0).Text = ItemCode Then
            item.SubItems(3).Text += ItemQty
            item.SubItems(5).Text += ItemPrice
            Return
        End If
    Next
    'Now if the For each fails doesn't find the record (fails to run the Return)
    ' normal listview insert codes run here
End Sub

Upvotes: 1

Related Questions