How to work with delegates and event handler for user control

Shantanu Gupta picture Shantanu Gupta · May 27, 2010 · Viewed 40k times · Source

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.

Answer

djdd87 picture djdd87 · May 27, 2010

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.