sashy

hi..
can anyone help me about my problem in listview, i'm trying to delete listview item that's already in my data table, the problem is every time the loop comes to last item of my listview i got an error.

this is my sample code:

For i = 0 To ListView1.Items.Count - 1
For Each Row As DataRow In Table.Rows
If Me.ListView1.Items(i).SubItems(2).Text().ToString = Row("UserID") Then
Me.ListView1.Items.RemoveAt(i)
End If
Next
Next i

thank you..


Re: Visual Basic General Listview Problem Please Help

~DigBoy~

The reason it's causing an error is because you are changing the collection while you are iterating through it. Try moving through the collection backwards. That way you will not be changing the position of items in the collection when you remove it (i.e. item #6 moves to position 5). Try this instead...

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

For x As Int32 = table.Rows.Count - 1 To 0 Step -1

If Me.ListView1.Items(i).SubItems(2).Text().ToString = table.Rows(x)("UserID") Then

Me.ListView1.Items.RemoveAt(i)

End If

Next

Next i





Re: Visual Basic General Listview Problem Please Help

sashy

I tried your codes yes its works but its still has an error ¡°Specified argument was out of range of valid values. Not valid for ¡®Display Index¡¯



Re: Visual Basic General Listview Problem Please Help

sashy

and the codes doesn't filter the first item




Re: Visual Basic General Listview Problem Please Help

~DigBoy~

Whoops! I changed the wrong For...Next loop. Obviously I should have been stepping backward the collection that you are manipulating -- the ListView Items collection, not the datarow collection. Try this instead...

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

For Each row As DataRow In table.Rows

If Me.ListView1.Items(i).SubItems(2).Text().ToString = row("UserID") Then

Me.ListView1.Items.RemoveAt(i)

End If

Next

Next i

If threr is still a problem with index not found or outside the bounds of the collection then you might also want to look at the Subitems collection to be sure there are always 3 (index position 2) subitems for each listview item.

Sorry about the confusion.





Re: Visual Basic General Listview Problem Please Help

sashy

thank you digboy..