The code is just dirty, due to sharing of the instance field
. 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:
Can you see the problem now?
So, to resolve the problem, you should avoid passing reference to the shared field; remove the field
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
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
In the handler code, type-cast
. It will also be the instance of the button clicked; now, extract an instance of the
from the button: takes
and type-cast it to
. Remove this instance of a panel.
Another solution is this: do it all in the code of the handler; extract an instance of
and type-cast this
: you can be sure that before deleting, this
is certainly the required
. Remove it.
It will work, too.
One more note: never ever use names like
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