Question

My program has multiple forms. The fifth and final form has a button that when clicked closes the application using the method Application.Exit(). However every time I click the button I receive the error 'cannot access a disposed object' surrounding this code on my first form:

 frm2 f2 = new frm2();
            this.Hide();
            f2.ShowDialog();
            this.Show();

The compiler indicates that the statement this.show() is the problem. Could someone explain why I am receiving this error and how to fix it?

No correct solution

OTHER TIPS

Ok edited my answer, I reproduced your issue. If you want to use Form.ShowDialog then you should set the DialogResult of the control that is closing the application. So in the buttons properties you should set the dialog result to something, for example Cancel.

Then on the buttons click event you would do something like this:

    private void btnClose_Click(object sender, EventArgs e)
    {
        if (this.DialogResult == DialogResult.Cancel)
        {
            Application.Exit();
        }
    }

Otherwise if you don't need to use Form.ShowDialog, you can just show Form2. The above does not produce the error in my testing.

In your code example, did frm2 make a call to Application.Exit? If it did, then why are you trying to call this.Show again?

Anyway, you may have a problem related to how you started the application's message loop. Are you running Application.Run(), or Application.Run(form1)?

If you provided a form to Application.Run() when you started your message loop, then you should not be calling Application.Exit in order to exit the application. Instead, you should simply close your main window, that would cause the message loop to finish, the call to Application.Run to return, and your application will terminate cleanly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top