2011-06-28 23 views
2

我已經創建一個userControl名稱是UserControl1。在這個用戶控件上,我創建一個按鈕名稱是btnAdd。我創建2表單名稱是Form1和Form2。然後我在這些表單上添加UserControl1。我想單擊Form1上的btnAdd按鈕,然後顯示字符串「this is form 1」,如果我單擊Form2上的btnAdd按鈕,然後顯示字符串「this is form 2」。如何在userControl中使用委託和事件?

我想使用委託和事件來做到這一點。你可以幫幫我嗎。 非常感謝。

我的代碼如下但未運行。真正的結果必須顯示在消息框「添加成功」:

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Drawing; 
using System.Data; 
using System.Text; 
using System.Windows.Forms; 

namespace EventDelegateUserControl 
{ 

    public partial class UC_them : UserControl 
    { 
     public UC_them() 
     { 
      InitializeComponent(); 
     } 
     public delegate void ThemClickHandler(object sender, EventArgs e); 
     public event ThemClickHandler ThemClick; 

     public void OnThemClick(EventArgs e) 
     { 
      if (ThemClick != null) 
      { 
       ThemClick(this,e); 
      } 
     } 
     public void add() 
     { 
      OnThemClick(EventArgs.Empty); 
     } 
     public void btnThem_Click(object sender, EventArgs e) 
     { 
      add(); 
     } 
    } 

//--------------------------- 

    public partial class Form1 : Form 
    { 

     public UC_them uc_them =new UC_them(); 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     public void dangky(UC_them uc_them) 
     { 
      uc_them.ThemClick += new UC_them.ThemClickHandler(uc_them_ThemClick);  
     } 

     void uc_them_ThemClick(object sender, EventArgs e) 
     { 
      MessageBox.Show("Add successful"); 
     } 
    } 

//---------------------------- 

static class Program 
    { 
     [STAThread] 
     static void Main() 
     { 
      Application.EnableVisualStyles(); 
      Application.SetCompatibleTextRenderingDefault(false); 
      Application.Run(new Form1()); 
      UC_them them = new UC_them(); 
      Form1 form1 = new Form1(); 
      form1.dangky(them); 
     } 
    } 

} 

回答

2

你的委託/事件相關的代碼是正確的。 Main方法的問題。

Application.Run(new Form1()); 
UC_them them = new UC_them(); 
Form1 form1 = new Form1(); 
form1.dangky(them); 

您在main方法中創建了兩個Form1實例。 Application.Run(第一個實例)方法中的一個實例,然後創建另一個實例。您只爲第二個實例設置事件綁定。但實際上只有第一例正在運行。

如果你改變你的主要方法如下,它應該工作。

static void Main() 
{ 
    Application.EnableVisualStyles(); 
    Application.SetCompatibleTextRenderingDefault(false);  

    UC_them them = new UC_them(); 
    Form1 form1 = new Form1(); 
    form1.dangky(them); 

    Application.Run(form1); 
}