-3

This portion of the application is a simple 'Add/Remove' rows of dynamically added controls. It's transportation software and the user is adding or removing line items to the order. Adding rows is working fine, however i'm now coding the remove portion and ran into this issue below. Each dynamically added control ends with a unique index pertaining to which row of items it belongs to. So the following code, should remove one row of 7 controls, all ending in the same index. However, it only removed about half of them, so i enclosed the FOR EACH in another FOR loop to hit the controls 4 times, AND NOW IT WORKS!?!? Each time i incremented the parent loop to hit the controls again, it removed a couple more, until the magic number 4 removed them all. What could be causing this?

For p As Integer = 1 To 4
    For Each c As Control In grpVehicles.Controls
        If c.Name.EndsWith(removeIndexClicked) Then
            grpVehicles.Controls.Remove(c)
        End If
    Next
Next
  • "should remove one row of 7 controls" - sounds that you're up for user control – T.S. Dec 14 '15 at 04:29
  • One thing I can tell you, if you want to loop collection, which you planning to modify in process of iterating, i.e. add/remove items - use `While` loop and never `For` loop – T.S. Dec 14 '15 at 04:31

1 Answers1

-3

You don't remove items from a list while enumerating that list, i.e. in a For Each loop. You either use a For loop and work backwards, e.g.

For i = myList.Count - 1 To 0 Step -1
    myList.RemoveAt(i)
Next

or you create a second list and enumerate that, e.g.

For Each item In myList.Where(Function(o) SomeContion(o)).ToArray()
    myList.Remove(item)
Next
jmcilhinney
  • 50,448
  • 5
  • 26
  • 46
  • 1
    You did see the duplicate link, right? – sstan Dec 14 '15 at 03:45
  • 1
    @sstan - I don't see any problem with answering a question while it remains open. – Enigmativity Dec 14 '15 at 03:55
  • 2
    @Enigmativity: See our community standard regarding duplicates here: [How should duplicate questions be handled?](http://meta.stackexchange.com/questions/10841/how-should-duplicate-questions-be-handled), specifically the section under **Should I answer it?**: *No, not if you think it's a duplicate. If you don't think the answers on the duplicate question are good enough, write an answer there. If you don't think the question is a duplicate, then by all means do answer it.* Not saying we all apply this guideline perfectly, I certainly don't. But I do think we should at least try. – sstan Dec 14 '15 at 13:24
  • On the other hand, see [Dr. Strangedupe: Or, How I Learned to Stop Worrying And Love Duplication](http://blog.stackoverflow.com/2010/11/dr-strangedupe-or-how-i-learned-to-stop-worrying-and-love-duplication/) – Ňɏssa Pøngjǣrdenlarp Dec 14 '15 at 13:54
  • 1
    @Plutonix: Interesting read, thanks. – sstan Dec 14 '15 at 13:58