Simple close form code

LabProARW

Well-known member
Joined
Nov 4, 2019
Messages
52
Programming Experience
1-3
I have a login form that runs first. Upon successful login I want to close this form and open Frm_Main. As a beginner in C# I'm having a problem with OOP and simply closing a form without closing the entire app. I'm working in Visual Studio 2017.

To be more specific, I have Program.cs that launches Frm_Login. I am trying to check for a successful login and then if Globals.LoginSuccess == true close the Frm_Login so that Program.cs can then launch the Frm_Main. Inside my if Globals.LoginSuccess loop I direct to my 'Btn_Cancel_Click which has a 'this.Close()'. The Btn_Cancel_Click works as it should to close Frm_Login when I click on it directly. Perhaps my problem is calling my Btn_Cancel_Click.

Thanks.
 
Last edited:
There's the correct way to do this, and the kludgey to do this.

The correct way to do this is to derive from the ApplicationContext. Basically, in your derived class, you'll start off with the MainForm set to your login form, and if the login is successful, set it to your Frm_Main. See Use the ApplicationContext Class to Fully Encapsulate Splash Screen Functionality. Although the CodeProject tutorial talks about splash screens and timers, the concepts are the same. You won't need the timer anymore and the event you'll be waiting for is for the login form to close and do the swap as appropriate.

On the other hand the kludgey way is simply have in main form's shown (or load event) go popup the login form. Then when the login form is dismissed, close the main form if the login is unsuccessful, or proceed normally if the login is successful.

As a quick aside, using global variables is a really poor idea, even if you are hiding your global state in a class called Globals.
 
Thank you for your response. In the base Program.cs the Frm_Login is called and the global variable LoginSuccess is generated inside that form. I was using Program.cs as the main code and using that global variable generated in Frm_Login to launch Frm_Main if the login was successful. I will look at the ApplicationContext Class tonight.
Thanks.
 
Back
Top Bottom