点击Form1的按钮,把文本框的值传给Form2。再点击Form2的按钮,把文本框的值传给Form1。
Form1代码:
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Windows.Forms; 9 10 namespace 委托传值 11 { 12 public partial class Form1 : Form 13 { 14 public Form1() 15 { 16 InitializeComponent(); 17 } 18 19 private void btn1_Click(object sender, EventArgs e) 20 { 21 Form2 frm2 = new Form2(txt1.Text,doSth);//Form2构造方法 22 frm2.Show(); 23 } 24 //把窗体2的字符串给窗体1 25 public void doSth(string msg) 26 { 27 txt1.Text = msg; 28 } 29 } 30 }
Form2的代码:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace 委托传值 { public delegate void MyDel(string str);//定义委托 public partial class Form2 : Form { public Form2() { InitializeComponent();//初始化窗体 } private MyDel _del;//实例化委托 public Form2(string str,MyDel del) { InitializeComponent();//初始化窗体 txt2.Text = str; this._del = del;//构造方法传参 } private void Form2_Load(object sender, EventArgs e) { } private void btn2_Click(object sender, EventArgs e) { //调用委托前先判定 if (this._del != null) { this._del(txt2.Text);//调用委托 } this.Close(); } } }