The code is just dirty, due to sharing of the instance field
Form1.dynamicPanel
. Very dirty. Just look carefully.
When the panel and deleting button is just one, everything is good, but if you try adding and removing panels in butterfly manner, the effect of sharing this variable comes into play. You think that you delete the panel having the button you are clicking on, but in fact the other instance of a panel is used, the one which was last added in this line:
FlowLayoutPanel1.Controls.Add(dynamicPanel)
Can you see the problem now?
So, to resolve the problem, you should avoid passing reference to the shared field; remove the field
Form1.dynamicPanel
at all. You need to pass data used by an event handle through the arguments of the event handler. Do something like this:
Add a back reference to a panel to the instance of deleting button, using its
Tag
property:
Private Sub btnAddPanel_Click(sender As System.Object, e As System.EventArgs) Handles btnAddPanel.Click
Dim btndeleteButton As Button
Dim dynamicPanel As Panel
dynamicPanel = New Panel
dynamicPanel.Size = New System.Drawing.Size(357, 100)
dynamicPanel.BackColor = Color.LightBlue
btndeleteButton = New Button
btndeleteButton.Tag = dynamicPanel
End Sub
In the handler code, type-cast
sender
to
Button
. It will also be the instance of the button clicked; now, extract an instance of the
Panel
from the button: takes
Button.Tag
and type-cast it to
Panel
. Remove this instance of a panel.
Problem solved.
Another solution is this: do it all in the code of the handler; extract an instance of
Button
by type-casting
sender
. Take
Button.Parent
and type-cast this
Control
to
Panel
: you can be sure that before deleting, this
Control
is certainly the required
Panel
. Remove it.
It will work, too.
[EDIT]
One more note: never ever use names like
btnAddPanel_Click
,
Form1
and other auto-generated names. Give everything some semantic names. This is why you are given the Visual Studio refactorization engine. No underscores or numerics ("Label1", "Label2" and the like). In addition to the problems of maintenance and readability, you are violating (good) Microsoft naming conventions. Yes, Microsoft auto-generated code violates them, too, so what? These names are not designed to be kept; you are supposed to rename them all, to make them semantically sensible.
—SA