Jackson
Jackson

Reputation: 51

Form.closed event is not firing

Whenever I click on form's red cross close button I want to display another form, but despite of having closed event handler, I'm unable to open another form.

This is how I'm trying to open another form:

private void Form1_Closed(object sender, System.EventArgs e)
{
     itemMaster.Show();

}

Could anyone please tell me how can I enable my requirment?

Upvotes: 4

Views: 10715

Answers (3)

Stacked
Stacked

Reputation: 7336

When you're done with your form and you want to close it(by clicking on a close button for example), be sure to use Close(). My form_closing event didn't fired because I used only Dispose() when clicking the close button.

I think the best way to close a form is to use both Close() and Dispose().

  • Close() => if you need to do something when closing the form...
  • Dispose() => to destroy the form (cleanup resources).

    private void _btnClose_Click(object sender, EventArgs e) { Close(); Dispose(); }

Upvotes: 1

First, you should use the FormClosed event instead of Closed:

The Closed event is obsolete in the .NET Framework version 2.0; use the FormClosed event instead.MSDN page for the Form.Closed event

void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
    // ...
}

Second, make sure that you have actually subscribed to Form1's FormClosed event:

Form1.FormClosed += Form1_FormClosed;

The Windows Forms designer should've automatically added a similar line somewhere in InitializeComponent. If not, that's why your handler method doesn't get called.

If this still doesn't help, try handling the FormClosing event insteaf of FormClosed.

Upvotes: 6

decyclone
decyclone

Reputation: 30840

If you have started your application with the following statement:

Application.Run(new Form1());

When you close Form1, your application will exit. Even if you open another form, it will be killed when application quits. Can you make sure this is the case by putting a breakpoint in your Form1_Closed method and see that the breakpoint is hit?

If this is the case, what happens is your code does execute but since the application quits, your another form also closes as soon as it opens.

To fix that, Hide() form1 instead of closing it. Handle Form_Closing event and call this.Hide() and set e.Cancel = true.

Upvotes: 4

Related Questions