I have a parent form FormSubscribingToTheEvent and a child form FormThatThrowsTheEvent
The child form has a button. When the button is clicked on the child form, I wish the parent form to be notified and the MessageBox to show the message: "The Close button was clicked."
I found the post: "Pass click event of child control to the parent control" Pass click event of child control to the parent control and I followed Reza Aghaei's instructions, which is the only and accepted answer.
Unfortunately, I get the error message: "An unhandled exception of type 'System.StackOverflowException' occurred in PassClickEventOfChildControlToTheParentControl.exe"
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace PassClickEventOfChildControlToTheParentControl
{
public partial class FormSubscribingToTheEvent : Form
{
public FormSubscribingToTheEvent()
{
InitializeComponent();
FormThatThrowsTheEvent instanceOfFormThatThrowsTheEvent = new FormThatThrowsTheEvent();
instanceOfFormThatThrowsTheEvent.CloseButtonClicked += new EventHandler(instanceOfFormThatThrowsTheEvent.CloseButton_Click);
instanceOfFormThatThrowsTheEvent.Show();
}
private void InstanceOfFormThatThrowsTheEvent_CloseButtonClicked(object sender, EventArgs e)
{
MessageBox.Show("The Close button was clicked.");
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace PassClickEventOfChildControlToTheParentControl
{
public partial class FormThatThrowsTheEvent : Form
{
public event EventHandler CloseButtonClicked;
public FormThatThrowsTheEvent()
{
InitializeComponent();
}
public void CloseButton_Click(object sender, EventArgs e)
{
OnCloseButtonClicked(e); // !!! An unhandled exception of type 'System.StackOverflowException' occurred in PassClickEventOfChildControlToTheParentControl.exe
}
/// <summary>
/// To raise the XXXX event, it is enough to invoke the XXXX event delegate.
/// the reason for 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.
/// </summary>
/// <param name="e"></param>
protected virtual void OnCloseButtonClicked(EventArgs e)
{
CloseButtonClicked.Invoke(this, e); // !!! An unhandled exception of type 'System.StackOverflowException' occurred in PassClickEventOfChildControlToTheParentControl.exe
}
}
}
Please explain what I am doing wrong and how I can correct the code so that the parent form gets notified of the button click event on the child form and the MessageBox to show the message: "The Close button was clicked."