Blog Archives

C# Event Handlers and Delegates in ASP .Net with Web User Controls

This article should help as a general how to on event handlers and delegates in C# as well as propose a different way to handle cross page methods in your ASP .Net website from a web user control or other page.

Page contains user control which has some methods and functionality built in. When a particular button click or other generic event is fired in the user control, it needs to call back to the parent page.

Create event handlers and their delegates in the user control, fire them from the methods tied to the internal controls protected events, and define the methods that will handle the new events in the page (see code below).

C# (with some VB notes):

//delegate declaration not necessary in VB
 public delegate void MyCustomHandler(object sender, EventArgs e);
    public event MyCustomHandler SomethingClicked;

    protected void btnButton1_Click(object sender, EventArgs e)
//tell our parent page which is listening for the event that something was clicked
//this null check and method invoke is the equivalent of raise event in VB
        if (SomethingClicked != null)
            SomethingClicked(sender, e);

//do some other work specific to this button in the user control

That’s the code for your user control, now for the page.

 protected void Page_Load(object sender, EventArgs e)

        MyUserControl1.SomethingClicked += new MyUserControl1.MyCustomHandler(MyUserControl1_SomethingClicked);

        if (!Page.IsPostBack)
            //do my other normal work


    protected void MyUserControl1_SomethingClicked(object sender, EventArgs e)
//voila! clicking on the button in your user control will fire this method on the parent page!

Alternatively instead of declaring your own delegate, you can also simply use:

//in control
public event EventHandler SomethingClicked;

//and in page load
MyUserControl1.SomethingClicked+= new EventHandler(MyUserControl1_SomethingClicked);

If you have no need for custom arguments, this a good quick alternative that may be well liked by VB users where delegate declaration is optional.

MSDN (events and delegates),
MSDN (dynamically bind event handlers),
MSDN (which control raised an event),
ASP.Net (blog),