Jacklovely

导航

 

说明(2017-5-30 11:38:06):

1. 窗体1传值到窗体2,只要实例化Form2,“Form2 frm2 = new Form2(txt1.Text)”,这里要给Form2加一个带参数的重载,并且继承this,因为要初始化。把txt1.Text传入窗体2接收就可以了。

2. 窗体2再传值回窗体1,就要用到委托了,因为不是传值,而是传方法(如果再实例化一个Form1,那就是打开一个新窗口了)。

(1)在Form1里加一个方法ShowMsg,作用是将参数msg赋值给txt1.Text。

(2)在Form2里新建一个委托,参数是一个字符串msg,给Form2的重载加一个委托参数mdl,当Form1里实例化Form2的时候,可以将ShowMsg方法一起传给Form2.

(3)在Form2里增加一个MyDel类型的字段_mdl,在Form2的重载里,将这个字段等于参数mdl(也就是将来要传进来的ShowMsg)。

(4)在Form2的button里,先判断委托是否存在,然后调用this._mdl,也就是ShowMsg,将txt2.Text的值传给txt1.Text,然后关闭Form2.

3. 其实挺绕的,多写几遍吧!

代码:

Form1.cs

 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel;
 4 using System.Data;
 5 using System.Drawing;
 6 using System.Linq;
 7 using System.Text;
 8 using System.Threading.Tasks;
 9 using System.Windows.Forms;
10 
11 namespace _06委托窗体传值
12 {
13     
14     public partial class Form1 : Form
15     {
16         public Form1()
17         {
18             InitializeComponent();
19         }
20         
21         private void button1_Click(object sender, EventArgs e)
22         {
23             Form2 frm2 = new Form2(txt1.Text, ShowMsg);
24             frm2.ShowDialog();
25         }
26         public void ShowMsg(string msg)
27         {
28             txt1.Text = msg;
29         }
30     }
31 }

Form2.cs

 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel;
 4 using System.Data;
 5 using System.Drawing;
 6 using System.Linq;
 7 using System.Text;
 8 using System.Threading.Tasks;
 9 using System.Windows.Forms;
10 
11 namespace _06委托窗体传值
12 {
13     public delegate void MyDel(string msg);
14     public partial class Form2 : Form
15     {
16         public Form2()
17         {
18             InitializeComponent();
19         }
20         private MyDel _mdl;
21         public Form2(string str,MyDel mdl):this()
22         { 
23             txt2.Text = str;
24             this._mdl = mdl;
25         }
26 
27         private void button1_Click(object sender, EventArgs e)
28         {
29             if (this._mdl != null)
30             {
31                 this._mdl(txt2.Text);
32                 this.Close();
33             }
34         }
35     }
36 }

窗体:

效果:

 

posted on 2017-05-30 11:54  Jacklovely  阅读(598)  评论(0编辑  收藏  举报