Mharveen Biu
Mharveen Biu

Reputation: 325

Getting the index of an item inside listview vb.net

how do i get the index of an item inside the listview by looping?

for i = 0 to Listview1.items.count -1
       ??????????????????
next

so that i can get the index and validate it. i know how to get the index using selectedindices. i really wanna know how to get the index in a looping method

just want to clarify

i was working on a listview that have a hotkeys from keypress 0 to 9 when keypress 0 is pressed, item1 will be inserted inside the listview and if i pressed 0 again the quantity column will increment, i manage to do that. but the problem is when i press keypress 1 first (which has the item2) it will go inside the listview then if i press keypress 0 im having an error because of the incriminating of the quantity. i think finding the index and loop it will solve the problem.

this is how i manage to incriment the quantity of the item1 in column 4 or element(3)

Dim quantity As Integer = CInt(cartListView.Items(0).SubItems.Item(3).Text)
quantity = quantity + 1
cartListView.Items(0).SubItems.Item(3).Text = quantity.ToString

of course the index(0) gives me error when the item1 is in the index 1 of the listview please be reminded that the item1 is static or fixed in the keypress 1. any solution or revision?

Solved: since the item1 is static, the looping statement that vlad gave does it. it manage to search the item1 and return the index and inserted that index to the element 0 of this code

Dim textSearch = DTfsn.Rows(0)("item1").ToString 'static item for keypress 1
For i = 0 To cartListView.Items.Count - 1
     If cartListView.Items(i).Text = textSearch Then
         Dim quantity As Integer = CInt(cartListView.Items(i).SubItems.Item(3).Text)
         quantity = quantity + 1
         cartListView.Items(i).SubItems.Item(3).Text = quantity.ToString
      End If
 Next

now it can increase its quantity whereever the item1 is positioned in the listview.

Upvotes: 1

Views: 2086

Answers (1)

Vland
Vland

Reputation: 4262

starting from this comment

of course. i wanna know how to get the index of a searched item

I'll just guess

if you want to find the index of a specific item (in the example I'm searching for item d)

enter image description here

you can do something like this:

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click


    Dim textSearch = TextBox1.Text 'text to look for

    For i = 0 To ListView1.Items.Count - 1

        If ListView1.Items(i).Text = textSearch Then
            MessageBox.Show("text found at index " & i.ToString)
        End If

    Next

End Sub

enter image description here

Upvotes: 1

Related Questions