问题描述
我有一个父表单 FormSubscribingToTheEvent 和一个子表单 FormThatThrowsTheEvent
子窗体有一个按钮。当单击子窗体上的按钮时,我希望通知父窗体并且 MessageBox 显示消息:"The Close button was clicked."
我找到了帖子:“将子控件的点击事件传递给父控件” Pass click event of child control to the parent control 并且我遵循了 Reza Aghaei 的说明,这是唯一且可接受的答案。
不幸的是,我收到错误消息:"An unhandled exception of type 'System.StackOverflowException' occurred in PassClickEventOfChildControlToTheParentControl.exe"
代码:
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
}
}
}
请解释我做错了什么,以及如何更正代码,以便父窗体收到子窗体上的按钮单击事件和 MessageBox 的通知以显示消息:"The Close button was clicked."
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)