Winform中利用委托實現窗體之間的傳值


下面我實現一個最簡單的頁面傳值功能,相信初學者能一看就明白。

點擊打開按扭,打開傳輸值窗體

View Code
 1 public partial class Form1 : Form
 2     {
 3         public Form1()
 4         {
 5             InitializeComponent();
 6         }
 7 
 8         public void getValue(string strV)
 9         {
10             this.textBox1.Text = strV;
11         }
12 
13         private void button1_Click(object sender, EventArgs e)
14         {
15             Form2 frm = new Form2();
16             //frm.fatherform = this;//將當前窗體賦給fatherform
17             //frm.getTextHandler += new Form2.GetTextHandler(getValue);//給事件賦值(注意:GetText方法的參數必須與GetTextHandler委托的參數一樣,方可委托)
18             frm.getTextHandler = getValue;//將方法賦給委托對象
19             frm.ShowDialog();
20         }
21     }

 

輸入值后點擊傳輸按扭,'value'將顯示在接收值窗體的TextBox上

View Code
 1 public partial class Form2 : Form
 2     {
 3         public Form2()
 4         {
 5             InitializeComponent();
 6         }
 7         //public Form1 fatherform;
 8 
 9         public delegate void GetTextHandler(string text);//聲明委托
10        // public event GetTextHandler getTextHandler = null;//定義委托事件
11        public  GetTextHandler getTextHandler;//委托對象
12         private void button1_Click(object sender, EventArgs e)
13         {
14             //if (fatherform != null)
15             //{
16             //    fatherform.getValue(this.textBox1.Text.Trim());
17             //    this.Close();
18             //}
19             if (getTextHandler != null)
20             {
21                 getTextHandler(this.textBox1.Text.Trim());
22                 this.Close();
23             }
24         }
25     }

這里主要為大家呈現了兩種傳值方式:

一、將Form1窗體傳給fatherform對象,隨后我們就可以在Form2中操作Form1了。
二、使用委托,將getValue方法賦給事件或委托對象getTextHandler,那么實現getValue操作就不用自己去做了因為已經委托給getTextHandler,直接調用getTextHandler即可

 


免責聲明!

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



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