第一种方法:将Form1整个窗体做为值传给Form2this
form1 button1弹出 from2,spa
from2 numericUpDown1的值改变,使form1 textBox1的值改变。code
Form1代码:orm
//第一种方法:将整个窗体做为值传给Form2 private void button1_Click(object sender, EventArgs e) { Form frm2 = new Form2(this); frm2.ShowDialog(); } //改变textBox1的值 public void ChangeText(string s) { this.textBox1.Text = s; }
Form2代码:blog
//将传过来的Form1所有赋值给f1,这样就能够在这边调用Form1了 private Form1 f1; public Form2(Form1 frm1) { InitializeComponent(); f1 = frm1; } private void numericUpDown1_ValueChanged(object sender, EventArgs e) { //调用Form1中的changetext事件 f1.ChangeText(numericUpDown1.Value.ToString()); }
第二种方法:委托与事件事件
form1 button1弹出 from2,get
from2 numericUpDown1的值改变,使form1 textBox1的值改变,string
from2 numericUpDown1的值清空,使form1 textBox1的值清空。it
Form1代码:event
//2.注册事件 private void button1_Click(object sender, EventArgs e) { Form3 frm3 = new Form3(); //写到+=时,按两次Tab键会自动生成frm3_changed,frm3_empty两个事件 frm3.UpdateTextValueEvent += new Form3.ChangeTextValueDelegate(frm3_changed);//改变值的事件 frm3.EmptyTextValueEvent += new Form3.ChangeTextValueDelegate(frm3_empty);//清空值的事件 frm3.ShowDialog(); } //改变值的事件 private void frm3_changed(string s) { this.textBox1.Text = s; } //清空值的事件 private void frm3_empty(string s) { this.textBox1.Text = ""; }
Form3代码:
//1.定义带参数的委托与两个事件 public delegate void ChangeTextValueDelegate(string s); public event ChangeTextValueDelegate UpdateTextValueEvent; public event ChangeTextValueDelegate EmptyTextValueEvent; //3.传值 private void numericUpDown1_ValueChanged(object sender, EventArgs e) { UpdateTextValueEvent(numericUpDown1.Value.ToString()); } private void button1_Click(object sender, EventArgs e) { EmptyTextValueEvent(numericUpDown1.Value.ToString()); }