本文实例讲述了C#简单实现子窗体向父窗体传值的方法。分享给大家供大家参考。具体如下:
击Form1的button1 打开Form2
再点击Form2的button2
在button2_Click事件中 通过this.Owner将Form2的textBox2的值设置给Form1的textBox1
并关闭Form2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click( object sender, EventArgs e) { Form2 frm2 = new Form2(); frm2.Show( this ); //或 frm2.ShowDialog(this); ////或者 //Form2 frm2 = new Form2(); //frm2.Owner = this; //frm2.Show();//或 frm2.ShowDialog(); } } public partial class Form2 : Form { public Form2() { InitializeComponent(); } private void button2_Click( object sender, EventArgs e) { Form1 frm1 = (Form1) this .Owner; //注意 如果textBox1是放在panel1中的 则先找panel1 再找textBox1 ((TextBox)frm1.Controls[ "textBox1" ]).Text = this .textBox2.Text; this .Close(); } } |
点击Form1的button1 打开Form2
再点击Form2的button2
在button2_Click事件中 通过this.Owner及调用父窗体Form1的公开属性或方法
将Form2的textBox2的值设置给Form1的textBox1
并关闭Form2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
public partial class Form1 : Form { public Form1() { InitializeComponent(); } public string TextBox1Text { set { this .textBox1.Text = value; } get { return this .textBox1.Text; } } private void button1_Click( object sender, EventArgs e) { Form2 frm2 = new Form2(); frm2.Show( this ); //或 frm2.ShowDialog(this); ////或者 //Form2 frm2 = new Form2(); //frm2.Owner = this; //frm2.Show();//或 frm2.ShowDialog(); } } public partial class Form2 : Form { public Form2() { InitializeComponent(); } private void button2_Click( object sender, EventArgs e) { Form1 frm1 = (Form1) this .Owner; frm1.TextBox1Text = this .textBox2.Text; this .Close(); } } |
希望本文所述对大家的C#程序设计有所帮助。