RomoveItem

I am trying to remove an item form a list box by selecting the item and clicking a button with the following code.  If I click on any item in the list other then the last one I get a error 381 (invalid property array index). Please help.

Private Sub cmdDelete_Click()
For intcounter = 0 To lstMain.ListCount - 1
If lstMain.Selected(intcounter) = True Then
lstMain.RemoveItem (intcounter)
End If
Next intcounter
End Sub
mad3654Asked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
paulstampConnect With a Mentor Commented:
A simple remedy for your code (assuming single select in your listbox) is to add Exit For into your loop :

Private Sub cmdDelete_Click()
For intcounter = 0 To lstMain.ListCount - 1
If lstMain.Selected(intcounter) = True Then
    lstMain.RemoveItem (intcounter)
    Exit For
End If
Next intcounter
End Sub

0
 
imurphy76Commented:
Try this instead:

Private Sub cmdDelete_Click()
lstMain.RemoveItem lstMain.ListIndex
End Sub
0
 
imurphy76Commented:
Private Sub cmdDelete_Click()
lstMain.RemoveItem lstMain.ListIndex
End Sub

0
Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

 
VbmasterCommented:
The correct way to remove the selected items from a multiselect-able listbox is using code like

   For intcounter = (lstMain.ListCount - 1) To 0
      If (lstMain.Selected(intcounter)) Then
         Call lstMain.RemoveItem(intcounter)
      End If
   Next

If you want to know why you got that problem with your old code.. it's because let's say you have a list with 3 items. You select the first item and then run the code. You first checks the first item, you see it is selected and removes it. Now you have a list of 2 items, and you check the 2nd item in the new list. Then you try to check the 3rd item (because you think that the list is 3 items) but there aint no such item and therefore you get that OutOfRange error.

Hope this helps.
0
 
paulstampCommented:
VBMaster.. don't you need a STEP -1 in your loop ??
0
 
VbmasterCommented:
Oops! Ye, to mad[blaha]: you need to add " Step -1" at the end of the For statement if you use the code from me.
0
 
mad3654Author Commented:
Thanks for the explaination also.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.