Search code examples
tabsuser-controlsdispose

NullReferenceException when Disposing UserControl in Tab


I am using C# WinForms.

I am using a usercontrol called AGauge. http://www.codearteng.com/2012/08/agauge-winforms-gauge-control.html I added the control to one of the tab pages in the Design view.

If I close the window without opening the tab page that contains the control, then I get a NullReferenceException (NullReferenceException occurred in AGauge.dll -- Object reference not set to an instance of an object)

If I open the tab page and then close the window, then everything works fine.

The exception happens in the Dispose() function when executing base.Dispose(disposing)

Since I don't have any view into the code in AGauge.dll, I am unsure what to do. I suppose I can create the controls at run-time when the tab page is opened, but that is not ideal.


Solution

  • I fixed the issue by creating the user control in the Selected() function of the tab control.

    private void tb_Panel_Selected(object sender, TabControlEventArgs e)
    {
        if (myUserControl == null)
        {
            this.myUserControl = new System.Windows.Forms.AGauge();
            ...
            ...
            this.Panel.Controls.Add(this.myUserControl)
        }
    }