窗体间传值有多种方法,这里我们接着上一篇的委托和事件,使用委托和事件实现窗体间传值。
运行结果:点击主窗体Form1按钮后,弹出子窗体Form2,在Form2的TextBox中输入字符串后点击按钮后,在主窗体使用Label显示。
声明委托:
public delegate void SendEventHandler(string msg) ;
Form1.cs:
///
<summary>
///
打开子窗体
///</summary>
///<param name="sender"></param>
///<param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.sendMsgEvent += new SendEventHandler(LabelChanged);
f2.Show();
}
///<summary>
///
接收来自子窗体的值,改变Label中的值
///</summary>
///<param name="msg"></param>
public void LabelChanged(string msg)
{
this.label1.Text = msg;
}
Form2.cs:
声明事件:
public
event SendEventHandler sendMsgEvent = null;
///<summary>
///
将值传到主窗体
///</summary>
///<param name="sender"></param>
///<param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
if (sendMsgEvent != null)
sendMsgEvent(this.textBox1.Text);
this.Close();
}
点击
button
后,将
Form2
中的值传递到
Form1
中,执行
sendMsgEvent
事件,其本质就是调用
Form1
的
LabelChanged
方法,达到传值的目的。