C#學習筆記(9)——委託(表單傳值)

來源:互聯網
上載者:User

標籤:.sh   等於   mode   c#   his   initial   分享   bsp   draw   

說明(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 : Form15     {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 : Form15     {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 }

表單:

效果:

 

C#學習筆記(9)——委託(表單傳值)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.