Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass click event of child control to the parent control

I have a Windows form, having a pane, which contains another class, derived from Windows Forms. This is contained as a control within the pane. It contains two buttons within itself.

I'd like the events of the child control to be passed all the way to the parent window. For example, the child window in the pane has a Cancel button, which is supposed to close it. I'd like the parent control, i.e., the main window to close as well, but how can I intercept the button click event of the child control?

I can modify the child control, but only if there is no other way to achieve this in a proper way, I'd rather like to avoid it.

like image 930
user1173240 Avatar asked Mar 21 '16 10:03

user1173240


1 Answers

While you can interact with parent form directly from child, It's better to raise some events by child control and subscribe for the events in parent form.

Raise event from Child:

public event EventHandler CloseButtonClicked;
protected virtual void OnCloseButtonClicked(EventArgs e)
{
    CloseButtonClicked.Invoke(this, e);
}
private void CloseButton_Click(object sender, EventArgs e)
{
    //While you can call `this.ParentForm.Close()` but it's better to raise the event
    //Then handle the event in the form and call this.Close()

    OnCloseButtonClicked(e);
}

Note: To raise the XXXX event, that's enough to invoke the XXXX event delegate; the reason of creating the protected virtual OnXXXX is just to follow the pattern to let the derivers override the method and customize the behavior before/after raising the event.

Subscribe and use event in Parent:

//Subscribe for event using designer or in constructor or form load
this.userControl11.CloseButtonClicked += userControl11_CloseButtonClicked;

//Close the form when you received the notification
private void userControl11_CloseButtonClicked(object sender, EventArgs e)
{
    this.Close();
}

To learn more about events, take a look at:

  • Handling and raising events
  • Standard .NET event pattern
like image 90
Reza Aghaei Avatar answered Nov 17 '22 19:11

Reza Aghaei