Form returns null after returning to the original custom control

I am new to Windows Forms and am having a problem handling all custom controls. I have 3 custom controls and when I click the Accept button it takes me to the second screen (which is custom control 2) but then when I click Cancel on the second screen it takes me back to the first screen (I load the first user control again) the problem is that when I click "Accept" again, the welcome user control returns null and errors.

private void Viewer_Load (object sender, EventArgs e) {formPanel.Controls.Clear (); formPanel.Controls.Add (wei); }

    private void SwapControls(object sender, EventArgs e)
    {
        if (formPanel.Controls.Contains(wel))
        {
            formPanel.Controls.Remove(wel);
            formPanel.Controls.Add(p);
        }
        else if (formPanel.Controls.Contains(pin) && IsAuthenticated)
        {
            formPanel.Controls.Remove(p);
            formPanel.Controls.Add(m);
        }
        else if(formPanel.Controls.Contains(pin) && !Global.IsAuthenticated)
        {
            formPanel.Controls.Remove(p);
            formPanel.Controls.Add(wel);
        }

      

So the first time it loads the welcome user control, then I click "Accept" and it clears the user control and loads the second "Enter Pin Control", from there when I click "Cancel" I remove that user control and download Welcome again. BUT now when I click "Accept" I am getting null on this line in the welcome user control

 this.AddControl(this, new EventArgs());

      

Again, I am new to window forms and I am learning, any inputs would be much appreciated.

+3


source to share


1 answer


Since you are reusing UserControls

, do not remove handlers when you remove from Form

, just make sure you remove them when you are done using UserControls

.

Try something like this.

private void SwapControls(object sender, EventArgs e) 
{ 
    if (formPanel.Controls.Contains(wel)) 
    { 
        formPanel.Controls.Remove(wel); 
        formPanel.Controls.Add(pin); 
    } 
    else if (formPanel.Controls.Contains(pin) && Global.Instance.IsAuthenticated) 
    { 
        formPanel.Controls.Remove(pin); 
        formPanel.Controls.Add(mmenu); 
    } 
    else 
    { 
        formPanel.Controls.Remove(pin); 
        formPanel.Controls.Add(wel); 
    } 
} 

      




/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
    wel.AddControl -= new EventHandler(SwapControls);
    pin.AddControl -= new EventHandler(SwapControls);
    pin.ReturnWelcome -= new EventHandler(SwapControls); 

    if (disposing && (components != null))
    {
        components.Dispose();
    }
    base.Dispose(disposing);
}

      

+3


source







All Articles