开发者

Delete Controls inside GroupBox

I created a groupbox and then populate it with buttons during runtime. I also created a button, say Button1 to loop through the groupbox and delete those buttons. Here's 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 only removes some of the controls inside the GroupBox1, not all. Can you explain what is missing in my code to make it work? Thanks.


When you delete controls in a For Each loop, you're actually modifying the collection that you're trying to loop through. When you remove the first item in the collection, the second item moves up to become the first. But now, when you reach the second index of your loop, the third item is in its place. You've effectively skipped removing the second item, and only removed the first and third. And so on through the entire loop.

Instead, you need to loop through the controls in reverse order and remove the item at each index. By starting to removing items from the end, you won't affect the order or position of the items.

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


You are changing the collection as you are itterating through it, and that 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜