表單間傳值(委託)

來源:互聯網
上載者:User

標籤:

  表單間的傳值很常用(還記得當時困擾了我好久。。。),有幾種方式都可以實現,這裡採用委託的方式。

 

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 : Form16     {17         public Form1()18         {19             InitializeComponent();20         }21 22         //設定文字框的text23         private void SetTextBox1Value(string str)24         {25             this.textBox1.Text = str;26         }27 28         //開啟Form229         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 : Form13     {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 其它的我不知道的使用情境

 

表單間傳值(委託)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.