2017-04-09 27 views
0

我在下面的UserControl中創建ButtonClick事件,並希望在窗體中處理它,但我得到一個錯誤,說'名稱UserControl1.ButtonClick'在當前上下文中不存在。在C#中的UserControl中創建一個ButtonClick事件#

public partial class UserControl1 : UserControl 
{ 
     public UserControl1() 
    { 
     InitializeComponent(); 
    } 
     public event EventHandler ButtonClick; 


    private void btnUpdate_Click(object sender, EventArgs e) 
    { 
     if (this.ButtonClick != null) 
      this.ButtonClick(this, e); 
    } 

形式:

 UserControl1.ButtonClick += new EventHandler(UserControl_ButtonClick); 



    protected void UserControl_ButtonClick(object sender, EventArgs e) 
    { 
     //handle the event 
    } 
+0

難道是你試圖使用類本身而不是實例嗎?在UserControl1.ButtonClick + = new EventHandler(UserControl_ButtonClick)行中;' –

+0

謝謝。我實例化,但該實例甚至無法使用。這兩個課程都是公開的,這個活動也是公開的。我確實建立了與Form相同的項目的UserControl1類。 – mercredi

+0

@mercredi - 你真的應該使用'var bc = this.ButtonClick;如果(bc!= null)bc(this,e);'而不是if(this.ButtonClick!= null)this.ButtonClick(this,e);'調用你的事件,因爲前者是線程安全的,後者不是。 – Enigmativity

回答

0

形式:

public PatientNumber() 
     { 
      InitializeComponent(); 
      userControl11.updateButton.Click += button_Click; 
     } 

     protected void button_Click(object sender, EventArgs e) 
     { 
        //handle the event 
     } 

用戶控件:

public Button btnUpdatee 
{ 
    get 
    { 
     return btnUpdate; 
    } 
    set 
    { 
     btnUpdate = value; 
    } 
} 

此代碼工作。 謝謝