关于WinForm窗体之间通过委托实现传参

关于winform窗体之间传递参数,其实有很多种方法,今天我想给大家介绍一种通过委托的方法在窗体之间进行参数传递。首先我先介绍一下实现的效果窗体1

窗体1打开窗体2时,将窗体1中的textBox中的值传递给窗体2中的textbox中,窗体2关闭窗体时,将窗体2中textbox修改的值回传给窗体1

窗体1的值传给窗体2时,实现很简单。窗体1中button的代码:

1 private void button1_Click(object sender, EventArgs e)
2         {
3             Form2 f2 = new Form2(textBox1.Text);
4             f2.ShowDialog();
5         }
View Code

窗体2的代码:

1 public Form2(string val) : this()
2         {
3             this.textBox1.Text = val;
4         }
View Code

这样窗体1往窗体2中传递参数就很轻松的实现了。那么重点来了,窗体2关闭窗体时往窗体1回传参数就有点难了,下面我就介绍用委托的方法进行窗体之间传值。

窗体1中的完整代码:

 1 namespace WinForm窗体传值
 2 {
 3     public partial class Form1 : Form
 4     {
 5         public Form1()
 6         {
 7             InitializeComponent();
 8         }
 9 
10         private void button1_Click(object sender, EventArgs e)
11         {
12             Form2 f2 = new Form2(textBox1.Text, UpdateTextBox);
13             f2.ShowDialog();
14         }
15 
16         private void UpdateTextBox(string val)
17         {
18             this.textBox1.Text = val;
19         }
20     }
21     //定义一个委托
22     public delegate void UpdateTextDelegate(string val);
23 }
View Code

窗体2中的完整代码:

 1 namespace WinForm窗体传值
 2 {
 3     public partial class Form2 : Form
 4     {
 5         public Form2()
 6         {
 7             InitializeComponent();
 8         }
 9 
10         //通过委托进行传值
11         public Form2(string val ,UpdateTextDelegate updateText) : this()
12         {
13             this.textBox1.Text = val;
14             this._updateText = updateText;
15         }
16 
17         //先声明一个委托变量:
18         private UpdateTextDelegate _updateText;
19 
20         private void button1_Click(object sender, EventArgs e)
21         {
22             this._updateText(this.textBox1.Text);
23             this.Close();
24         }
25 
26     }
27 }
View Code

 其中,要注意的是委托其实就是一个类型和class是一个级别,可以将委托当成一个变量进行传递。

猜你喜欢

转载自www.cnblogs.com/liuyongfei-521/p/9090694.html