在C#中使用委託 .

 
  1. 要求如下:  
  2.     在窗體Form1、Form2中各有一個文本框、一個按鈕,現在我需要點擊Form1中的按鈕,彈出窗體Form2,然後在窗體Form2中的文本框中輸入字符串,然後點擊Form2中的按鈕,將文本框中的值傳到Form1中的文本框中。  
  3.   
  4. 【第一種方法:】  
  5. 窗體Form2中的代碼如下:  
  6.         public delegate void SendDate(object sender);  
  7.   
  8.         public SendDate sendDate;  
  9.   
  10.         private void button1_Click(object sender, EventArgs e)  
  11.         {  
  12.             if (sendDate != null) {  
  13.                 sendDate(rtxtValue.Text);//注意:在這裏還可以傳入一個控件,比如:sendDate(rtxtValue)   
  14.             }  
  15.             this.Close();  
  16.         }  
  17.   
  18. 窗體Form1中的代碼如下:  
  19.      private void button1_Click(object sender, EventArgs e)  
  20.          {  
  21.             Form4 f = new Form4();  
  22.             f.sendDate = new Form4.SendDate(Funcation);  
  23.             f.ShowDialog();  
  24.          }  
  25.   
  26.   
  27.          private void Funcation(object sender)  
  28.          {  
  29.             this.textBox1.Text = sender.ToString();  
  30.        //this.textBox1.Text=((TextBox)sender).Text;   
  31.          }  
  32.   
  33.   
  34. 【第二種方法:】  
  35. Form2:  
  36.     public delegate void SendMsg(string msg);  
  37.     private void button1_Click(object sender, EventArgs e)  
  38.          {  
  39.                     Form1 f = new Form1();  
  40.                     SendMsg sm = new SendMsg(f.getMsg);  
  41.                 sm(textBox1.Text);  
  42.                     this.Close();  
  43.     }  
  44. Form1:  
  45.        public void getMsg(string msg)  
  46.            {           
  47.                    MessageBox.Show(msg);  
  48.          }  
  49.   
  50.           private void button1_Click(object sender, EventArgs e)  
  51.           {  
  52.               Form2 f = new Form2();         
  53.                f.Show();  
  54.             }  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章