Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dispose login form and show main form after username and password are entered on login form

Tags:

c#

forms

dispose

I run LoginForm using the code below:

[STAThread]
static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new LoginForm());
    //Application.Run(new MainForm());
}

When user presses the enter button, i want to dispose or close the LoginForm and want to run the MainForm but i got this exception: "InvalidOperationException was unhandled by user code"

Click handler of the enter button is given below:

private void LoginFormEnterButton_Click(object sender, EventArgs e)
{
    try
    {
        MainForm a = new MainForm();
        a.Show();
        this.Close();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}

What can i do to dispose the LoginForm and after that to run the MainForm successfully?

like image 300
sanchop22 Avatar asked Jan 24 '26 20:01

sanchop22


1 Answers

You can't dispose the Main window. You need to change the way.

First of all set MainForm as startup window.

Application.Run(new MainForm());

Load/show the LoginForm in constructor of MainForm,

public MainForm()
{
 LoginForm login=new LoginForm();
 login.ShowDialog();
 InitializeComponent();
}

and Click handler code in LoginForm,

private void LoginFormEnterButton_Click(object sender, EventArgs e)
{
   this.Close();
}
like image 65
KV Prajapati Avatar answered Jan 27 '26 08:01

KV Prajapati



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!