I have two forms in my project (Login and Main).
What I'm trying to accoomplish is, if the login is successful, I must show the Main form and close the Login form.
I have this method in Login form that closes the Login form when the login is successful. But the Main form doesn't show.
public void ShowMain()
{
if(auth()) // a method that returns true when the user exists.
{
var main = new Main();
main.Show();
this.Close();
}
else
{
MessageBox.Show("Invalid login details.");
}
}
I tried hiding the Login form if the login process is successful. But it bothers me because I know while my program is running the login form is still there too, it should be closed right?
What should be the right approach for this? Thanks...
It's simple.
Here is the code.
This is my solution. Create ApplicationContext to set mainform of application and change mainform when you want to open new form and close current form.
Program.cs
When login process is complete.
I hope this will help you.
you should do it the other way round:
Load the
mainform
first and in itsonload
event show yourloginform
withshowdialog()
which will preventmainform
from showing until you have a result from theloginform
EDIT: As this is a login form and if you do not need any variables from your
mainform
(which is bad design in practice), you should really implement it in your program.cs as Davide and Cody suggested.best way for show login for and close login form before login successfully put login form in FrmMain after InitializeComponent.
This is the most elegant solution.
;-)
I would do this the other way round.
In the OnLoad event for your Main form show the Logon form as a dialog. If the dialog result of that is OK then allow Main to continue loading, if the result is authentication failure then abort the load and show the message box.
EDIT Code sample(s)
Another solution would be to show the LogonForm from the Main method in program.cs, something like this:
In this example your LogonForm would have to expose out a LogonSuccessful bool property that is set to true when the user has entered valid credentials