Malfist
Malfist

Reputation: 31815

Why can I not close a form in C#?

I cannot close one of my forms programmatically. Can someone help me?

Here's the code:

    private void WriteCheck_Load(object sender, EventArgs e) {
        SelectBankAccountDialog sbad = new SelectBankAccountDialog();
        DialogResult result = sbad.ShowDialog();
        if (result == DialogResult.Cancel) {
            this.Close();
        } else {
            MessageBox.Show(result.ToString());
        }
        MessageBox.Show(sbad.bankaccountID.ToString());
    }

Upvotes: 0

Views: 4059

Answers (3)

johnc
johnc

Reputation: 40233

As configurator mentioned (in comments), the form must be shown before it can be closed, so, instead of the Load event, you should be doing this in the Shown event instead.

If you don't want the form visible for the Dialog box, I guess you can wrap the event code in a Visible = false;

In summary, the basic code would be

    private void WriteCheck_Shown(object sender, EventArgs e)
    {
        Visible = false;
        SelectBankAccountDialog sbad = new SelectBankAccountDialog();
        DialogResult result = sbad.ShowDialog();
        if (result == DialogResult.Cancel) {
            this.Close();
        } else {
            MessageBox.Show(result.ToString());
        }
        MessageBox.Show(sbad.bankaccountID.ToString());
        Visible = true;
    }

Upvotes: 4

Malfist
Malfist

Reputation: 31815

The actual problem is that windows won't let a form close on it's load method. I have to show the dialog on construction, and then if the dialog result is cancel I have to throw an exception and catch the exception on form creation.

This place talks more about it

Upvotes: 0

lc.
lc.

Reputation: 116528

By calling Form.Close(), the form should close, but not until all waiting events have been processed. You also still have a chance to cancel the form closing in the FormClosing event.

First, you'll probably want to return after your call to this.Close(). If it still doesn't close, step through your code and see what is happening. You may have to set and check a "forciblyClose" flag and return from any other processing methods before it'll actually close.

Upvotes: 3

Related Questions