Link to home
Start Free TrialLog in
Avatar of Stephent
Stephent

asked on

Removing Multiple Selected Items from a ListView

Hi

How do I remove multiple selected items from a ListView.

I have two listviews. One procedure copies mutliple selections from one listview to the second listview. If I then want to removed multiple selections from the second list view I have the following code

Private Sub cmdRemove_Click()
Dim i As Integer
Dim a As Integer

For i = 1 To lvplan.ListItems.Count
    If lvplan.ListItems(i).Selected = True Then
        a = lvplan.ListItems(i).SubItems(2)
        lvActivityLog.ListItems(a).SmallIcon = 2
        lvplan.ListItems.Remove (i)
    End If
Next

End Sub

The problem occures because when one of the items is removed. For example if I have three items and I am loop through them and remove one then when I come to the third the index no longer exists and I get
Index Out of Bounds
Error message.

I'm I going about it the wrong way? High points because I need a quick answer.

Cheers,
Stephen
Avatar of magglass1
magglass1

Try reversing the for loop so that it removes items at the end first.  Something like...

Private Sub cmdRemove_Click()
Dim i As Integer
Dim a As Integer

For i = lvplan.ListItems.Count To 1
   If lvplan.ListItems(i).Selected = True Then
       a = lvplan.ListItems(i).SubItems(2)
       lvActivityLog.ListItems(a).SmallIcon = 2
       lvplan.ListItems.Remove (i)
   End If
Next

End Sub
ASKER CERTIFIED SOLUTION
Avatar of JoaTex
JoaTex

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Forgot to put Step -1 in the For loop in my reply.  Sorry.
Avatar of Stephent

ASKER

Cheers Jo it worked excellently.

Sorry magglass few minutes earlier and the points were yours. Shame I can't split the points.

Stephen