利用事件进行窗体之间传值
今天做了一个小例子,实现在winform中利用事件在两个窗体之间进行传值,加深了对事件的运用和理解。
现在附上原创代码,如果有不完善的地方,还望大家指导和完善,谢谢!
Form 1
Cs:
namespace EventTest
{
public partial class Form1 : Form
{
public delegate void valueChangeHandle(string value); //定义一个委托
public static event valueChangeHandle valueChangeEvent; //定义事件
public Form1()
{
InitializeComponent();
Form2.valueHandle += new Form2.ValueHandle(form2_valueHandle);
}
#region 方法
private void btnUp1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.Show();
if (valueChangeEvent !=null) //如果有对象注册
{
valueChangeEvent(txtUp1.Text); //调用所有注册对象的方法
}
}
void form2_valueHandle(string str)
{
txtDown1.Text = str;
}
#endregion
}
}
Form 2
Cs:
namespace EventTest
{
public partial class Form2 : Form
{
public delegate void ValueHandle(string str);
public static event ValueHandle valueHandle;
public Form2()
{
InitializeComponent();
Form1.valueChangeEvent += new Form1.valueChangeHandle(GetForm1Txt_valueChangeEvent); // 注册方法
}
void GetForm1Txt_valueChangeEvent(string value)
{
txtDown2.Text = value;
}
private void btnUp2_Click(object sender, EventArgs e)
{
if (valueHandle != null)
{
valueHandle(txtDown2.Text);
this.Close();
}
}
}
}