Windows Form父子两个窗体之间的传值测试

1:先看测试的效果图:

 

2:全部的代码

 1 using System;
 2 using System.Windows.Forms;
 3 
 4 namespace WindowsForms
 5 {
 6     public partial class ParentForm : Form
 7     {
 8         public void ParentGetvalue(string text)
 9         {
10            this.textBox1.Text = text; 
11             labelp.Text ="获取的值是:"+ text;
12         }
13         public Action<string> doinvokeP;
14         private void ParentForm_Load(object sender, EventArgs e)
15         {
16             ChildForm cf = new ChildForm(this);
17             doinvokeP += cf.ChildGetValue;  cf.Show();
18         }
19         private void btnParent_Click(object sender, EventArgs e)
20         {
21             if (doinvokeP != null)
22             {
23                 doinvokeP.Invoke(textBox1.Text);
24             }
25         }
26 
27         public ParentForm()
28         {
29             InitializeComponent();
30         }
31     }
32 }
View Code
 1 using System;
 2 using System.Windows.Forms;
 3 
 4 namespace WindowsForms
 5 {
 6     public partial class ChildForm : Form
 7     {
 8         public ParentForm cpform;
 9         public void ChildGetValue(string msg)
10         {
11             textBoxC.Text = msg;
12         }
13         public ChildForm(ParentForm cpform)
14         {
15             this.cpform = cpform;
16             InitializeComponent();
17         }
18 
19         private void btnChild_Click(object sender, EventArgs e)
20         {
21             if (cpform!=null)
22             {
23                 this.cpform.ParentGetvalue(textBoxC.Text);
24             }
25         }
26     }
27 }
View Code

 

3:总结

 由父到子窗体使用了委托,但是反过来由子到父,一样对应的逻辑,就是不行,后来调式打印,值都传递过去了,就是不行,浪费了一些时间!

     最后发现是父窗体根本就不是同一个对象的问题,看来还是要细心才行,欢迎大家有更好的建议,谢谢!

 

posted @ 2019-12-03 10:52  天天向上518  阅读(240)  评论(0编辑  收藏  举报