天天看点

C#通过委托从子窗体向父窗体传值

C#通过委托从子窗体向父窗体传值

1.Form1中(父窗体):

1 using System;
 2 using System.Windows.Forms;
 3 
 4 namespace WindowsForms跨窗体传值大全
 5 {
 6     public partial class Form1 : Form
 7     {
 8         public Form1()
 9         {
10             InitializeComponent();
11         }
12 
13         private void button1_Click(object sender, EventArgs e)
14         {
15             Form2 f2 = new Form2();
16             f2.ChangeText += new ChangeTextHandler(Change_Text);//将事件和处理方法绑在一起,这句话必须放在f2.ShowDialog();前面
17             f2.ShowDialog();            
18         }
19 
20        public void Change_Text(string str)
21         {
22             textBox1.Text = str;
23         }  
24     }
25 }
           

2.Form中(子窗体):

1 using System;
 2 using System.Windows.Forms;
 3 
 4 namespace WindowsForms跨窗体传值大全
 5 {
 6     public delegate void ChangeTextHandler(string str);  //定义委托
 7 
 8     public partial class Form2 : Form
 9     {
10         public Form2()
11         {
12             InitializeComponent();
13         }
14 
15         public event ChangeTextHandler ChangeText;  //定义事件
16 
17         private void button2_Click(object sender, EventArgs e)
18         {
19             if (ChangeText != null)//判断事件是否为空
20             {
21                 ChangeText(textBox2.Text);//执行委托实例  
22                 this.Close();
23             }           
24         }    
25     }
26 }
           
引用自https://www.cnblogs.com/xh6300/p/6063649.html