Delete controls inside GroupBox

I created a group package and then populated it with buttons at runtime. I also created a button, such as Button1, to skip the group package and remove these buttons. Here is my code for Button1:

Public Sub removeControls() For Each ctrl As Control In GroupBox1.Controls GroupBox1.Controls.Remove(ctrl) ctrl.Dispose() Next End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click removeControls() End Sub 

When executed, it deletes only some controls inside GroupBox1, but not all. Can you explain what is missing in my code to make it work? Thanks.

+4
source share
2 answers

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 
+5
source

You change the collection as it repeats through it, and this should not be done.

Rather use something like

 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 
+2
source

All Articles