3
votes

I am new to Windows forms and having an issue handling all the user controls. I have 3 User Controls, and when I click a accept button it takes me to the second screen (which is user control 2) but then when I click cancel on the second screen it brings me back to the first screen (I load the first user control again) the issue now is that when I click again "Accept" the welcome user control returns null and errors.

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

    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 around it loads up the welcome user control, then there I click "Accept" and it clears the User control and loads up the second one "Enter Pin Control", from there when I click "Cancel" I remove that User Control and Load up again Welcome. BUT now, when I click Accept, I get a null in this line in the welcome user control

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

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

1

1 Answers

3
votes

Since you are reusing your UserControls don't remove the handlers when you remove them from the Form, just make sure you remove them when you are finished using your 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);
}