When you delete controls in a For Each loop, you are actually modifying the collection that you are trying to execute. . When you delete the first item in the collection, the second item moves up to become the first. But now that you have reached the second index of your cycle, the third element is in its place. You actually skipped deleting the second item and only deleted the first and third. And so on through the whole cycle.
Instead, you need to skip the controls in reverse order and delete the item in each index. . Starting to delete elements from the end, you will not affect the order or position of the elements.
So, just change your method to the following:
Public Sub RemoveControls() For i As Integer = (GroupBox1.Controls.Count - 1) To 0 Step -1 Dim ctrl As Control = GroupBox1.Controls(i) GroupBox1.Controls.Remove(ctrl) ctrl.Dispose() Next i End Sub
source share