开发者

Correctly removing control from FlowLayoutPanel

How do I correctly dispose an user control in a Flow开发者_如何学编程LayoutPanel ?

Does flowlayoutpanel1.Controls.RemoveAt(i) suffice?

I just can't find a .Dispose() for flowlayoutpanel1.Controls...


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();


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.


If the control has Dispose() method just call it after removing it from the panel.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜