Search code examples
c#formswinformsuser-interfacepanel

How do I transition between forms C# Winforms?


This may seem like a rather obvious and extremely newcomer question (and it is), but I've merely been attempting to transition between multiple forms in C# Winforms and somehow managed to encounter numerous complications:

  1. To begin, I used the obvious:
frm_hub hub = new frm_hub();
hub.Show();

However, each time this code run, a new instance of frm_hub was created and using hub.Close(); would not work because it was not closing the same new instance of frm_hub

  • Is a way to close the same instance of a form from a different form - say with a global variable? Or is there some way to integrate a Close(); so the entire program continues to function and new form displays?
  1. As a possible solution to the above issue, I tried to store the same form as a variable:
frm_hub hub = new frm_hub();
private void OpenForm()
{
    hub.Show()
}

However the runtime error: 'System.StackOverflowException: 'Exception of type 'System.StackOverflowException' was thrown.' was showing when I attempted to use this same tactic of storing the form as a variable in the two forms.

  • Why is this error occurring? And is there any way I can overcome it?
  1. Finally, during some reading to counter this issue I discovered the use of controls and panels, and in this way, I could create an interface that opens different the different forms in a panel

However, my attempt of this required the use of anchors to get the form to display remotely true to the Designer appearance

  • If I do not require the form to be resizable, how can use panels to display a different form and at that in a way that displays the design elements how I have them positioned

Apologies again for my beginner understanding and use of terminology, feel free to seek clarification for crucial details I probably haven't included haha, Thank you!


Solution

  • I used the following, not sure it's best practice. I used a button ShowFrmHubButton and disabled it when the window is already shown.

    In my example the second form is modal, and you can't use the first window as long as the second is displayed.

    ShowFrmHubButton.IsEnabled = false;
    var frmHubWindow = new frm_hub ()
    {
        Owner = this
    };
    
    frmHubWindow.ShowDialog();
    ShowFrmHubButton.IsEnabled = true;
    

    Then, when you close\cancel the second form use this.Close();