Link to home
Start Free TrialLog in
Avatar of fisherbrsnch00
fisherbrsnch00

asked on

Removing item from Listbox Using ItemData

Basically I have two listboxes. When the user clicks the add button, selected items are removed from one and added to the other, it works both ways.

I have no problem adding selected items from one listbox to the other but the problem comes when I try to remove an item. Here is the code:
-----------------------------------------------------------
Dim index As Integer

For index = 0 To ListTables.ListCount - 1

If ListTables.Selected(index) = True Then
    ListSelectedTables.AddItem (ListTables.List(index))
    ListTables.RemoveItem (index)
End If

Next index
-----------------------------------------------------------

The problem occurs after an item is removed. I get an "Invalid propery array index" error when the index is referenced after. I believe that the problem has to do with the fact that the listcount and indexes are changed once an item is removed, but it is still in a loop. Anyway, I know that the item data property is used so that a specific number is assigned to each item so that it does not matter what order they are in and can still be referenced. Problem is I can not remember how to use it through code.

Can someone please give a quick example of using item data to reference items in a listbox and/or if there is a better way without using it.

This question is urgent, thank you.

Avatar of anv
anv

u need to change your loop use the following instead

dim LstCountas integer

LstCount = ListTables.ListCount - 1

For index = 0 To LstCount

If ListTables.Selected(index) = True Then
    ListSelectedTables.AddItem (ListTables.List(index))
    ListTables.RemoveItem (index)
End If

LstCount = LstTables.ListCount - 1
Next

The LstTables.Listcount That u use in the for loop doesnot change even if u r removing items..either u use While loop or use above loop for ur code and test it..
Avatar of fisherbrsnch00

ASKER

With that code I get the same error
ASKER CERTIFIED SOLUTION
Avatar of anv
anv

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
Missed the statement

If index >= List1.ListCount - 1 Then Exit For

Sorry..:)
Thank you, works great!