Search code examples
c#winformsdispose

WinForm disposing a sub form when the form is disposed


I have a form that can open a sub form (with ShowDialog). I want to make sure that the sub form is being disposed properly when the main form is done. I tried adding the subform to the components member of the main form, but at the moment I got a ArgumentNullException.
I know I can just instantiate the components myself, but isn't that a bit dangerous? One day I'll add a component in the designer view, and that will generate the new Container() line in the designer.cs file, and I'll never know I have two component instanses running around the heap.
Is there an easier way to make sure the sub form is being disposed?

EDIT - moved my solution to an answer


Solution

  • My current workaround:
    I've added the Components property to the form, and am using it to access the collection

    private IContainer Components{    get { return components ?? (components = new Container());}}