首先拖一个用户控件:
public partial class MyControl : UserControl
{
public MyControl()
{
InitializeComponent();
}
public event EventHandler<MyButtonEvent> MyBtnClick;//定义一个用户控件的事件
//用户控件中通过Button的Click事件触发自定义事件
private void button1_Click(object sender, EventArgs e)
{
//将用户控件中TextBox的文本内容,传给事件MyButtonEvent
MyBtnClick(sender, new MyButtonEvent(this.textBox2.Text));
}
}
上面这个类是用户控件的
public class MyButtonEvent : EventArgs
{
private object sender;
public MyButtonEvent()//空构造,必须有
{
}
public MyButtonEvent(object sender)//带参数的构造
{
this.sender = sender;
}
public string GetStr()//外部通过e点出来的方法
{
return sender.ToString();
}
}
先生成一下解决方案,你就会看到在Form中拖入的用户控件就会多了一个MyBtnClick事件,双击就和我们平常用的Click事件一样用了。
在Form窗体中拖入一个上面建好的用户控件MyControl 和一个TextBox->textBox1
private void myControl1_MyBtnClick(object sender, MyButtonEvent e)//自定义事件
{
this.textBox1.Text = e.GetStr();
}
以上代码通过自定义事件的形式,将用户控件中的值传给父窗体