This document introduces events and event handling in ASP.NET, and probes into how you can effectively use them to extend the functionality of your Web applications.
An event is basically a notification sent by an object to signal the occurrence of some given condition, for which you can provide a response. ASP.NET includes a predefined set of Web Forms events, that can be caused by either:
- the system ( such as when a page loads or a control is rendered ), or
- some form of user interaction with the controls on the page ( such as when a user clicks on a button ) .
We use events to trigger some specified action when the event occurs. To do so, we supply an event handler, and attach or "register" the handler with the event source, basically in the following notation:
<control id="controlID" runat="server" ... eventName="eventhandlerName" />
An event handler is essentially a method or function written in any of the .NET programming languages, that receives control whenever the designated event occurs. Event-handling methods can be as simple as changing the text of a control, or as involved as processing complex data operations at the click of a button.
Some events are internally wired up to default handlers, such as when the page initializes, loads, and unloads, or when we click on a submit button that automatically sends the page back to the server. ASP.NET, though, allows us the flexibility to define and attach our own event handlers that will also be called whenever the event occurs.
For example, this simple code fragment renders a button at run time that posts the form back to the server when clicked. By defining and assigning a handler to the button’s Click event, we are in effect directing the page framework to take some action in response to the event. Upon each postback at the server then caused by the event, the framework runs the ShowHide method, and sends the generated page output back to the client.
<asp:button runat="server" onClick="ShowHide" />
The below example illustrates this concept, and shows how you can respond to page and control events using simple event handlers.
On page load, the Text property of the <asp:Button
> is initialized.
Whenever the button’s Click event occurs, the method ShowHide is called, which conditionally shows or hides the contents of an <asp:Panel
> control.
The panel contains an <asp:AdRotator
> and an <asp:HyperLink
> control. Whenever the AdCreated event ocurs, the method getAdProps is invoked, and the selected ad’s AlternateText and NavigateUrl properties are used to set the hyperlink’s text and destination link, respectively.