Share via


How to: Dynamically Bind Event Handlers at Run Time in ASP.NET Web Forms Pages

If a page already contains an event-handling method with the appropriate signature, you can bind a control event to it at run time. You commonly do this when you are creating controls programmatically.

To create an event handler at run time by using Visual Basic

  • Include an AddHandler Statement, passing it the event to bind and the address of the method to call.

    Be sure that the statement is executed before the event can be raised. Typically, you add handlers during page initialization.

    The following code example shows how to bind the Click event of the Button1 control to a method named myEventHandler:

    AddHandler Button1.Click, AddressOf myEventHandler
    

To create an event handler at run time by using Visual C#

  1. Create an instance of the EventHandler delegate, passing to it the address of the method to bind to.

  2. Add the delegate object to the list of methods that are called when the event is raised.

    The following code example shows how to bind the Click event of the Button1 control to a method named myEventHandler:

    Button1.Click += new System.EventHandler(this.myEventHandler);
    

See Also

Concepts

ASP.NET Web Forms Server Control Event Model

Other Resources

Server Event Handling in ASP.NET Web Forms Pages

Adding ASP.NET Controls Programmatically