How do i raise an event in a usercontrol and catch it in mainpage?

前端 未结 3 438
小鲜肉
小鲜肉 2020-12-02 06:58

I have a UserControl, and I need to notify the parent page that a button in the UserControl was clicked. How do I raise an event in the UserC

3条回答
  •  一整个雨季
    2020-12-02 07:27

    Check out Event Bubbling -- http://msdn.microsoft.com/en-us/library/aa719644%28vs.71%29.aspx

    Example:

    User Control

    public event EventHandler StatusUpdated;
    
    private void FunctionThatRaisesEvent()
    {
        //Null check makes sure the main page is attached to the event
        if (this.StatusUpdated != null)
           this.StatusUpdated(this, new EventArgs());
    }
    

    Main Page/Form

    public void MyApp()
    {
         //USERCONTROL = your control with the StatusUpdated event
         this.USERCONTROL.StatusUpdated += new EventHandler(MyEventHandlerFunction_StatusUpdated);
    }
    
    public void MyEventHandlerFunction_StatusUpdated(object sender, EventArgs e)
    {
             //your code here
    }
    

提交回复
热议问题