Indeed it's a bad practice to Dispose()
an object to which there is a live reference (in your visual tree). If you want to remove the buttons, you perhaps have to remove them from Controls
in an orderly way. See http://msdn.microsoft.com/en-us/library/system.windows.forms.control.controlcollection.removeat.aspx.
Edit:
Please note that the button is an IDisposable
, therefore the version with RemoveAt
needs an explicit Dispose
:
var controls = flowLayoutPanel1.Controls;
for (int i = controls.Count - 1; i >= 0; --i)
{
var c = controls[i];
if (c is ButtonWithProperties)
{
flowLayoutPanel1.Controls.RemoveAt(i);
c.Dispose();
}
}
Edit:
The documentation suggests that Dispose
should be called even if one is using Clear
. So if you don't need the buttons any more, you should Dispose()
them.