I have a Panel control. And inside the panel users can add combobox's, textbox's labels etc and drag them around and stuff, and there's a Delete button on my form where if they click it, it will delete all controls inside that panel. BUT this code:
foreach( Control control in panel.Controls )
{
control.Dispose();
}
... Does not work properly. It doesn't always Dispose of ALL the controls inside the panel. Sometimes it gets rid of most of them, sometimes it only gets rid of one or two. Sometimes all but 1 are Disposed. WTF?
EDIT:
button1_Click(object sender, EventArgs e)
{
TextBox tbox = new TextBox();
tbox.Multiline = true;
tbox.IsAccessible = true;
panel.Controls.Add(tbox);
}
A simpler way to delete all your controls is to do this:
panel.Controls.Clear();
Edit: thanks to Pieter and Paolo, just calling Clear() like this will leak memory since the controls are not disposed, so this is not a good practice.