我正在使用Windows窗体C#
。
我有主Form
和孩子form
。该活动位于子Form
,我在主Form
订阅了此活动。问题是,当我单击子窗体中的button1
时,它什么都不做(它应该触发事件,因此textBox1
打印文本)因为事件仍然是null
,尽管主窗体已经订阅了这个活动。难道我做错了什么?请点击button1
点击后如何触发事件。
儿童表格:
public partial class ChildForm : Form
{
public event EventHandler MyEvent;
private void button1_Click(object sender, EventArgs e)
{
if (myEvent != null)
{
MyEvent(this, e);
}
}
主要表格:
public partial class MainForm : Form
{
ChildForm ChildFrm= new ChildForm ();
ChildFrm.MyEvent += new EventHandler(HandleTheEvent);
private void button1_Click(object sender, EventArgs e)
{
ChildForm childfrm = new ChildForm ();
childfrm.ShowDialog()
}
public void HandleTheEvent(object sender, EventArgs e)
{
textBox1.Text = "event is fired";
}
答案 0 :(得分:5)
您正在将事件处理程序添加到另一个ChildForm实例。将MainForm的button1_click更改为如下所示:
private void button1_Click(object sender, EventArgs e)
{
ChildFrm.ShowDialog()
}
您的应用程序应该可以正常工作。
这是有效的MainForm.cs:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
ChildFrm.MyEvent += new EventHandler(HandleTheEvent);
}
ChildForm ChildFrm = new ChildForm();
private void button1_Click(object sender, EventArgs e)
{
ChildFrm.ShowDialog();
}
public void HandleTheEvent(object sender, EventArgs e)
{
textBox1.Text = "event is fired";
}
}
答案 1 :(得分:1)
在创建表单后立即订阅活动:)
private void button1_Click(object sender, EventArgs e)
{
ChildForm childfrm = new ChildForm();
childfrm.MyEvent += new EventHandler(HandleTheEvent);
childfrm.ShowDialog()
}