1、构造函数传值,但这种方法是单向的(推荐)
上代码,先传值
1 2 3 4 5 6 7 8 9 10 11 12
| private void button2_Click(objectsender, EventArgs e) { Form3 fr3 = new Form3("要传的值啊"); fr3.ShowDialog(); } 接值,对了,这里需要重载一个Form3的构造函数,然后将拿到的值显示出来
public Form3(string canshu) { InitializeComponent(); label1.Text =canshu; }
|
2、静态变量传值(不推荐)
可以将静态变量申明在你需要的地方,比如一个单独类,或者Form中,比如我们在这里申明在Form2中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| public static string xvalue; private void button2_Click(objectsender, EventArgs e) { xvalue = "要传的值啊xvalue"; Form3 fr3 = newForm3(); fr3.ShowDialog(); } ``` 先给赋值,然后在Form3中取值 ```bash publicForm3() { InitializeComponent(); label1.Text = Form2.xvalue;//Form2实际也是个class,直接取静态值即可,如果静态变量xvalue定义在其他类中,即将Form2替换即可 }
|
3、通过共有属性传值
首先在要打开的Form中创建一个共有属性,然后在调用窗口赋值即可。比如下面Form2启动Form3,即给Form3的yvalue传值
(1)在Form3中定义共有属性
1 2 3 4 5 6 7 8
| public stringyvalue { get{ returnlabel1.Text.ToString(); } set{ label1.Text =value; } }
|
(2)Form2中启动Form3,并传值
1 2 3 4 5 6
| private void button2_Click(objectsender, EventArgs e) { Form3 fr3 = newForm3(); fr3.yvalue = "要传的值啊"; fr3.ShowDialog(); }
|
4、通过Owner属性传值
(1)在调用者Form2中申明一个公有变量,并赋值,设置需要启动的Form3的Owner
1 2 3 4 5 6 7 8
| public stringxvalue; private void button2_Click(objectsender, EventArgs e) { xvalue = "Form2要传的值"; Form3 fr3 = newForm3(); fr3.Owner = this; fr3.ShowDialog(); }
|
(2)启动窗体Form3中取值
1 2 3 4 5
| private void Form3_Load(objectsender, EventArgs e) { Form2 fr2 = (Form2)this.Owner; label1.Text =fr2.xvalue; }
|
这种方法实际是将Form2传给了Form3,因此Form3可以取到Form2的所有公有变量和属性。
5、委托传值(推荐)
委托传值主要用在子窗体给父窗体传值上,即上文的Form3给Form2传值
(1)先在Form3中申明委托
1 2 3 4 5 6 7 8 9 10
| public delegate void PutHandler(stringtext); public PutHandler putTextHandler;//委托对象 private void button1_Click(objectsender, EventArgs e) { if (putTextHandler != null) { putTextHandler(textBox1.Text.ToString()); } }
|
(2)在Form2中绑定委托事件
1 2 3 4 5 6 7 8 9 10 11 12
| public void getValue(stringstrV) { this.textBox1.Text =strV; } private void button1_Click(objectsender, EventArgs e) { Form3 fr3 = newForm3(); fr3.putTextHandler =getValue; fr3.ShowDialog(); }
|