I build a ToolStripPanel
in code where I add a ToolStrip
and subsequently add several ToolStripButton
s and ToolStripSeparator
s. Do I need to manually go through and remove and/or call dispose on each of these? That is, loop through the buttons and separators and call dispose on them, then remove the ToolStrip
from the ToolStripPanel
and the dispose the ToolStrip
and finally remove the ToolStripPanel
from it's parent control and dispose of it?
UPDATE
Reading the documentation of Control.Dispose it appears that calling Dispose
on a parent will dispose of the children. What's not clear to is whether ToolStripItem
s are proper "children" of the ToolStrip
since you don't add them to the ToolStrip.Controls
collection but rather the ToolStrip.Items
collection. When looking at the ToolStrip.Controls documentation it says this property is not relevant to this class.
Same thing with the ToolStripPanel
as you don't call ToolStripPanel.Controls.Add(toolstrip)
but rather ToolStripPanel.Join(toolstrip)
.
Yes, ToolStripItems are treated as children. ToolStrip.Dispose() iterates the Items collection and disposes the items. The items are not added to the Controls collection because they are not classes that derive from Control. They are "window-less" controls and use their parent to render themselves. Which makes them very cheap.
ToolStripPanel.Join() does in fact add the ToolStrip to the Controls collection (ToolStrip does inherit from Control). It just needs to do one extra thing, it needs to move the strip in the right spot. And has 4 overloads.
So no extra work necessary, disposing the panel is enough to get its toolstrips and their items disposed as well.