NotQuiteThereYet
NotQuiteThereYet

Reputation: 497

Strange behavior when dynamically adding controls to a panel

[Using VB.NET 2010 / Winforms]

Note: my actual project is much more complex/useful than the code I posted below (the code below is just the minimal test case required to reproduce the weird behavior).

OK... In the Designer, I put 2 large, equally-sized panels on a form, named "ContainerA" and "ContainerB", along with a button (Button1). I put 5 small colored panels inside ContainerA (named RedPanel, BluePanel, GreenPanel, etc).

Nothing is inside ContainerB.

What I'm trying to do, upon Button1 click, is dynamically put all 5 of the small colored panels from ContainerA inside ContainerB. Simple, right? But for some strange reason, it only puts 3 of those panels in ContainerB! (and it leaves the remaining 2 panels inside ContainerA!

What in the heck is going on here? This is one of the weirdest things I've ever seen in the many years I've coded in .NET!

Here is my code for the button's click event...

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

    For Each ColorBlock As Panel In ContainerA.Controls
        ContainerB.Controls.Add(ColorBlock)
    Next

End Sub

Any ideas? I get the same strange (unexpected) behavior in both my real project, as well as the simple test project I posted above, so something weird is going on in VB.

Hopefully someone can shed some light on this, so I can stop banging my poor head against the wall trying to figure out the solution! :/

Upvotes: 0

Views: 73

Answers (1)

John Koerner
John Koerner

Reputation: 38079

You are removing the controls from the collection that you are looping over, so once you remove more than half of the controls, the loop will exit. To prevent this, loop backwards over the controls:

For i As Integer = ContainerA.Controls.Count - 1 To 0 Step -1
    Dim ColorBlock As Control = Panel1.Controls(i)
    ContainerB.Controls.Add(ColorBlock)
Next

Upvotes: 2

Related Questions