目的:把窗体2里面TextBox的值在点击button后传到窗体1 当中的lable中
实现:
新建一个窗体1,里面建一个 按钮 一个lable,给按钮注册一个点击事件大妈如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
public partial class Form1 : Form { public Form1() { InitializeComponent();//form1的构造函数 } private void button1_Click(object sender, EventArgs e) { Form2 frm2 = new Form2(ShowMsg);//通过构造函数传到From2 frm2.Show(); } void ShowMsg(string str)//赋值的方法 { label1.Text = str; } } |
再新建一个From2的窗体
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
//申明一个委托 public delegate void DelText(string str);//from1里面的方法 的委托 public partial class Form2 : Form { public DelText _del;//委托类型字段 public Form2(DelText del)//From2的构造函数(通过构造函数 把委托传递进来) { this._del = del;//赋值给字段 起到保存的作用 InitializeComponent(); } private void textBox1_TextChanged(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { _del(textBox1.Text);//把TextBox的值内容通过委托的方式传递给from1 } } |
不错