WK Integration Services Ltd

Seamless Solutions, Tailored Integration

Close a Parent Form from Child Form

Close a Parent Form from Child Form

From a child form I wanted to close the parent form after a button was clicked, the following is the code I used:

// In the child form, create an event that indicates the special occurrence.
public event EventHandler Special;
protected virtual void OnSpecial(EventArgs e) {
EventHandler Handler = Special;
if (Handler != null)
Handler(this, e);
}

// Perhaps a button Click is the event you want to indicate the Special event from.
protected void SomeButton_Click(object sender, EventArgs e) {
...
// After doing some stuff, fire the special event.
OnSpecial(EventArgs.Empty);
}

-----------------------------------

// * Back in the parent form.
...

// Create the child form and subscribe to its Special event.
ChildForm childForm = new ChildForm();
childForm.Special += new EventHandler(ParentForm_Special);

// Set the owner for the child form and show it.
childForm.Owner = this;
childForm.Show();

...

// The handler for the child form's Special event.
void ParentForm_Special(object sender, EventArgs e) {
// Close both forms.
ChildForm childForm = (ChildForm)sender;
childForm.Close();
this.Close();
}

Voila!

Leave a Reply

Your email address will not be published. Required fields are marked *