窗體間傳值(委托)


  窗體間的傳值很常用(還記得當時困擾了我好久。。。),有幾種方式都可以實現,這里采用委托的方式。

 

1.首先,建好兩個窗體,想要的效果如下。

2.看看里面的代碼

2.1 Form1的代碼

 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.Windows.Forms;
 9 
10 namespace 窗體傳值_委托_
11 {
12     //設置給 文本框賦值方法 的委托
13     public delegate void setTextBox1ValueDel(string str);
14 
15     public partial class Form1 : Form
16     {
17         public Form1()
18         {
19             InitializeComponent();
20         }
21 
22         //設置文本框的text
23         private void SetTextBox1Value(string str)
24         {
25             this.textBox1.Text = str;
26         }
27 
28         //打開Form2
29         private void btnOpenForm2_Click(object sender, EventArgs e)
30         {
31             Form2 frm = new Form2(SetTextBox1Value);
32             frm.ShowDialog();
33         }
34     }
35 }

 

2.2 Form2 的代碼

 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.Windows.Forms;
 9 
10 namespace 窗體傳值_委托_
11 {
12     public partial class Form2 : Form
13     {
14 
15         // 文本框賦值方法 的委托屬性
16         private setTextBox1ValueDel _setTextBox1ValueDel;
17 
18         public Form2(setTextBox1ValueDel del )
19         {
20             InitializeComponent();
21             this._setTextBox1ValueDel = del;
22         }
23 
24         //發送
25         private void btnSend_Click(object sender, EventArgs e)
26         {
27             _setTextBox1ValueDel(this.textBox1.Text);
28         }
29     }
30 }

3.到這里,問題已經解決了,可以關閉這個頁面了。如果你沒有成功,請看下面。

3.1委托

使用委托一共分三步:

1.定義

1.1看好了,setTextBox1ValueDel 直接定義在了命名空間下,而不是在某個類的下面。它代表的是一個方法的類型。

這個方法,沒有返回值,參數是一個string類型。

 

1.1.1 為什么這么定義呢,是根據我想要被調用的方法決定的。被調用的方法是沒有返回值的,只有一個string參數。

 

2.實例化

2.1 我在Form2的窗體里定義了一個setTextBox1ValueDel 類型的屬性。

 

2.2 setTextBox1ValueDel 委托有了,但它自己並不知道自己是哪一個方法的委托(我還是覺得用“代理”這個詞更好理解,某些語言中“委托”被稱作“代理”)。

所以有了下面的代碼:

2.2.1將方法名傳遞給Form2

2.2.2 Form2中的代理初始化

 

3.調用

3.1 現在可以調用了,傳入的是string

 

4.我這么啰嗦的,寫的這么詳細,只是為了使用委托進行窗體間的值的傳遞嗎?

4.1 線程

 我是在線程的使用中才了解委托的,下一篇我將介紹在線程中的使用。

。。。。。其實,線程中使用和這里一樣,我不過是想引出其它的知識點。

4.2 事件

我只知道,事件其實就是委托的一種形式。以后會自學下事件,然后再來分項。

4.3 其它的我不知道的使用場景

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM