Search code examples
c#winformsformclosing

About form closing at runtime in C#


I have two forms named frmRegistration & frmMain in my project in c#.

I have set frmRegistration as my start form.
User enters data in the frmRegistration form & presses submit button to get registered. Then, I want to close frmRegistration form & show frmMain form to the user.
I'm trying this by using Dispose() method of the frmRegistration. But, when I use this method, it disposes all my application execution because frmRegistration is the startup form.

I don't want this to happen. Can anyone solve this problem?

thanks.


Solution

  • Use Show() and Hide() methods.

        private void btnSubmit_Click(object sender, EventArgs e)
        {
          ...
          var frm = new frmMain();
          frm.Location = this.Location;
          frm.StartPosition = FormStartPosition.Manual;
          frm.Show();
          this.Hide();
        }  
    

    UPDATE:
    If you don't want to have frmRegistration in memory, start your program in main form and add this in your MainForm's Shown event:

        var frm = new frmRegistration();
        frm.Location = this.Location;
        frm.StartPosition = FormStartPosition.Manual;
        frm.FormClosing += delegate { this.Show(); };
        frm.Show();
        this.Hide();  
    

    Now you can just close the registration form and automatically get back to main form.