Search code examples
c#user-controlsevent-handlingdelegatescustom-event

How to work with delegates and event handler for user control


I have created a user control that contains a button. I am using this control on my winform which will be loaded at run time after fetching data from database.

Now I need to remove a row from a datatable on the Click event of that button.

The problem is that how do I capture that event in my form. Currently it goes in that user control's btn click event defination.


Solution

  • You can create your own delegate event by doing the following within your user control:

    public event UserControlClickHandler InnerButtonClick;
    public delegate void UserControlClickHandler (object sender, EventArgs e);
    

    You call the event from your handler using the following:

    protected void YourButton_Click(object sender, EventArgs e)
    {
       if (this.InnerButtonClick != null)
       {
          this.InnerButtonClick(sender, e);
       }
    }
    

    Then you can hook into the event using

    UserControl.InnerButtonClick+= // Etc.