How to remove listbox items in sync with another listbox

I have two listboxes that I need to modify together. It is broadly working, but there is a problem when it comes to removing items. I’m using code similar to the code below. Adding and editing items in listbox A results in the same items changing in listbox B. However, when I remove a listbox item from listbox A, I find that all but one of the matching listbox items are removed from listbox B. For example, if the item “One” appears once in listbox A and three times in listbox B, removing “One” in listbox A results in two of the three disappearing from listbox B. The last one remains in the list.

I think this might be because I am doing

for i as integer = 0 to listboxB.RowCount - 1
[…]
listboxB.removeRowAt(i)

and each time round the loop the RowCount is reducing by 1, so things may be getting out of sync.

I’m not sure what to do about this. Should I do the loop with a reducing counter, or is there something else I could do?

Here is the current code.

for i as integer = 0 to listB.RowCount - 1
  if listB.CellTextAt(i, 0) = tmpChoiceText then
    // Remove this row
    listB.RemoveRowAt(i)
    msgbox("Removed " + tmpChoiceText + " from position " + i.ToString + " in listA and listB")
  end if 
next

Any help appreciated.

Ian.

Reverse you’re for loop. After you have removed the first item the numbers of all the higher elements reduce by one. So the loop misses one

for i as integer = listB.LastRowIndex DownTo 0
  if listB.CellTextAt(i, 0) = tmpChoiceText then
    // Remove this row
    listB.RemoveRowAt(i)
    msgbox("Removed " + tmpChoiceText + " from position " + i.ToString + " in listA and listB")
  end if 
next

Always remove elements from the highest first.

Also Ian

1 Like

Perfect. Thank you.