Reputation: 11137
How do I correctly dispose an user control in a FlowLayoutPanel ?
Does flowlayoutpanel1.Controls.RemoveAt(i)
suffice?
I just can't find a .Dispose() for flowlayoutpanel1.Controls
...
Upvotes: 3
Views: 7159
Reputation: 79
If you wish to remove all the controls, you can iterate through the control collection backwards, rather than creating a copy (see below).
I have found this provides the best solution, particularly if you intend to re-populate it afterwards. Forcing GC to collect helps keep memory use in check where there are a large number of controls.
FlowLayoutPanel.SuspendLayout();
if (FlowLayoutPanel.Controls.Count > 0) {
for (int i = (FlowLayoutPanel.Controls.Count - 1); i >= 0; i--) {
Control c = FlowLayoutPanel.Controls[i];
c.SomeEvent -= SomeEvent_Handler;
c.Dispose();
}
GC.Collect();
}
FlowLayoutPanel.ResumeLayout();
Upvotes: 2
Reputation: 66389
If the control has Dispose()
method just call it after removing it from the panel.
Upvotes: 0
Reputation: 13577
Do you want to dispose all the controls in the FlowLayoutPanel
or all of them? If you want to dispose all of them, just dispose the FlowLayoutPanel
. Disposing a control disposes everything in the Controls collection as well. If you want to dispose an individual control, call that control's Dispose method; the FlowLayoutPanel
will automatically remove it from its Controls collection.
If you want to dispose all the controls, but not the FlowLayoutPanel
itself, it's a bit trickier. You can't just foreach over the Controls collection and dispose each control because that would cause the Controls collection to be modified. Instead, you could copy the Controls collection to a separate list and dispose of them from there.
Upvotes: 1