Section 3.1. Events

3.1. Events

The two models of program execution (which are not necessarily mutually exclusive) are linear and event-driven . The key to understanding ASP.NET is that it is event-driven.

Linear programs move from step 1, to step 2, and so on, to the end of all the steps. Flow control structures within the code (such as loops , if statements, or method calls) may redirect the flow of the program, but essentially , once the program execution begins, it runs its course unaffected by anything the user or system may do. Before GUI environments, most computer programs were linear.

In contrast, event-driven programming responds to something happening (such as a button being pressed). Most often, events are generated by user action, but events can be raised by the system. For example, the system might raise an event when a file that you open for reading has been read into memory or when your battery's power is running low.

In ASP.NET, objects may raise events and other objects may have assigned event handlers. For example, a button may raise the Click event, and the page may have a method to handle the button's click event (such as Button1_Click ). Your code in the event handler then responds to the button's being clicked in whatever way is appropriate for your application.

The main point to remember here is that server controls are objects that can raise events. Any action a user takes with a server control on the browser raises an event. Your server-side code responds to that event, running the code you have placed in the event handler method.

3.1.1. ASP.NET Events

ASP.NET has thousands of events. The application has events (such as Start and End ), each session has events (again, such as Start and End ), and the page and most of the server controls can raise events. All ASP.NET events are handled on the server. Some events cause an immediate posting to the server, and other events are stored until the next time the page is posted back to the server.

Because they are handled on the server, ASP.NET events are somewhat different from events in traditional client applications, in which both the event itself and the event handler are on the client. In ASP.NET applications, an event is typically raised on the client (such as by the user clicking a button displayed in the browser) but handled on the server.

Consider an ASP.NET web page with a button control. A Click event is raised when the button is clicked. Unlike an HTML button control, the ASP.NET button has an attribute, runat =server , that adds server-side processing to all the normal functionality of an HTML button.

When the Click event is raised once again, the browser handles the client-side event by posting the page to the server. This time, however, an event message is transmitted to the server. The server determines if the Click event has an event handler associated with it, and if it does, the event handler will be executed on the server.

An event message is transmitted to the server via an HTTP POST. ASP.NET automagically (that's a technical term ) handles all the mechanics of capturing the event, transmitting it to the server, and processing the event. As the programmer, all you have to do is create your event handlers .

Many events , such as MouseOver , are ineligible for server-side processing because they kill performance. All server-side processing requires a postback (a round trip to the server and back), and you do not want to post the page every time there is a MouseOver event. If these events are handled at all, it is on the client side (using script) and outside the scope of ASP.NET.

It is possible, and often useful, to endow server controls with client-side processing, as described later in this chapter. However, this is essentially an end run around the fundamental nature of ASP.NET.


3.1.2. Event Arguments

Events are implemented with delegates . A delegate is an object that encapsulates the description of a method to which you may assign responsibility for handling the event.

For a complete discussion of delegates, see Programming C# , Fourth Edition, by Jesse Liberty (O'Reilly).


By convention, all ASP.NET event handlers take two parameters and return void. The first parameter represents the object raising the event. By convention, it is called sender , though that is not a requirement. Using the sending object will be covered later in this chapter in the section on Programmatic Access to Controls.

The second parameter, called the event argument , contains information specific to the event if there is any. For most events, the event argument is of type EventArgs , which does not expose any properties. So, the general prototype for an event is the following:

 private void   EventName   (object sender, EventArgs e) 

For some controls, the event argument may be of a type derived from EventArgs and may expose properties specific to that event type. For example, the AdRotator control's AdCreated event handler receives an argument of type AdCreatedEventArgs , which has the properties AdProperties , AlternateText , ImageUrl , and NavigateUrl . The specifics of the event arguments for each control are detailed in the chapters describing each control.

3.1.3. Application and Session Events

ASP.NET supports the Application and Session events familiar to classic ASP programmers. An Application_Start event is raised when the application starts. This is a good time to initialize resources that will be used throughout the application, such as database connection strings (but not the database connection itself). An Application_End event is raised when the application ends. This is the time to close resources and do any other housekeeping that may be necessary. Garbage collection will automatically take care of freeing up memory, but if you allocated unmanaged resources, such as components created with languages that are noncompliant with the .NET Framework, you must clean them up yourself.

Likewise, there are session events. A session starts when a user first requests a page from your application and ends when the application closes the session or the session times out. A Session_Start event is raised when the session starts, at which time you can initialize resources that will be session-specific, such as opening a database connection, though it is probably better to open a database connection when it is needed and close it immediately when finished with it. When the session ends, there will be a Session_End event.

3.1.4. Page and Control Events

The page and controls all have events that are inherited from the Control class (or the TemplateControl class in the case of the Error event). All of these events pass an event argument of type EventArgs that exposes no properties. The most common of these events are listed in Table 3-1. (A complete list of all properties, methods , and events for every class can be found in the documentation.)

Table 3-1. Some common page and control events

Event name

Description

DataBinding

Occurs when the control binds to a data source

Disposed

Occurs when the control is released from memory

Error

For the page only; occurs when an unhandled exception is thrown

Init

Occurs when the control is initialized

Load

Occurs when the control is loaded to the Page object

PreRender

Occurs when the control is about to be rendered

Unload

Occurs when the control is unloaded from memory


Binding a control to a data source means that the control and the data source are tied together so that the control knows to use that data source for populating itself. Chapters 9 and 10 provide a complete description of data controls and data binding.


3.1.5. Postback Versus Non-Postback Events

Postback events cause the form to be posted back to the server immediately. These include click-type events, such as Button.Click . In contrast, many events (typically change events such as TextBox.TextChanged , or selection events, such as CheckBox.CheckedChanged ) are considered non-postback because the event is not posted back to the server immediately. Instead, these events are cached by the control until the next time a post occurs. Controls with non-postback events can be forced to behave in a postback manner by setting their AutoPostBack property to true .

Table 3-2 summarizes the controls with postback and non-postback events.

Table 3-2. Postback and non-postback controls

Postback

Non-postback

Button

BulletedList

Calendar

CheckBox

DataGrid

CheckBoxList

DataList

DropDownList

FileUpload

ListBox

GridView

RadioButtonList

ImageButton

RadioButton

ImageMap

TextBox

LinkButton

 

Menu

 

Repeater

 

3.1.6. IsPostBack

The Page object exposes the IsPostBack property. This is a read-only Boolean property that indicates if the page is being loaded for the first time or if it is being loaded in response to a client postback. There are many expensive operations (such as getting data from a database or populating ListItems) you will want to perform only the first time the page is loaded. If the page is posted to the server and then reloaded, there will be no need to repeat the operation, since any data entered or populated is retained (using view state, described in Chapter 6) on subsequent posts. By testing the value of IsPostBack , you can skip the expensive operation, as in the following code snippet:

  protected void Page_Load(Object sender, EventArgs e)  {  if (! IsPostBack)  {           //  Do the expensive operations only the           //  first time the page is loaded.        }     } 

3.1.7. Events in Visual Studio 2005

The Visual Studio 2005 (VS2005) IDE can automatically handle much of the work required to implement events in ASP.NET. For example, it offers a list of all the possible events for each control. If you choose to implement an event, you can type in a name for the event handler. The IDE will create the boilerplate code necessary and will wire up the associated delegate.

When you create a new web application, VS2005 automatically includes the following code snippet to handle the Page Load event:

 protected void Page_Load(object sender, EventArgs e)     {       } 

Every page has a number of events for which you may create handlers, similar to the Page_Load event handler. These predefined event handler names are created by concatenating Page_ with the name of the event. So, the following event handlers will automatically be hooked to their corresponding event:

Page_Load

Page_AbortTransaction

Page_CommitTransaction

Page_DataBinding

Page_Disposed

Page_Error

Page_Init

Page_InitComplete

Page_Load

Page_LoadComplete

Page_PreInit

Page_PreLoad

Page_PreRender

Page_PreRenderComplete

Page_SaveStateComplete

Page_Unload

In addition, controls placed on the page will have their own events that you may handle as well. When you add the control, you can see its events by clicking on the control in Design view and then clicking on the events button (the lightning bolt) in the Properties window. For example, the events for a Button control placed on the page are shown in Figure 3-1, with the events button indicated.

You can type the name of a method in the space next to any event or double-click in that space, and VS2005 will create an event handler for you. In either case, you'll be placed in the event handler, ready to type your code to implement the event, as shown in Figure 3-2.

In this case, I double-clicked in the space next to the Click event. VS2005 named the event Button1_Click ( ControlName_EventName ), created the skeleton of the event handler, and placed the cursor within that event handler.

Figure 3-1. Button events

Figure 3-2. Button event handler

Every control has a default event, presumably the event most commonly implemented for that control. Predictably, the default event for the Button class is the Click event. You can create the default event handler just by double-clicking on the control in Design view. Thus, had you not created the Button1_Click event handler, as shown above, you could open Design view and double-click on the button. The effect would be identical: an event handler named Button1_Click would be created, and you'd be placed in the event handler ready to type your code to implement the method.

The default event for some of the most common web controls are listed in Table 3-3.

Table 3-3. Default events for some ASP.NET controls

Control

Default event

AdRotator

AdCreated

BulletedList

Click

Button

Click

Calendar

SelectionChanged

CheckBox

CheckedChanged

CheckBoxList

SelectedIndexChanged

DataGrid

SelectedIndexChanged

DataList

SelectedIndexChanged

DropDownList

SelectedIndexChanged

HyperLink

Click

ImageButton

Click

ImageMap

Click

Label

None

LinkButton

Click

ListBox

SelectedIndexChanged

Menu

MenuItemClick

RadioButton

CheckedChanged

RadioButtonList

SelectedIndexChanged

Repeater

ItemCommand


3.1.8. Multiple Controls to One Event Handler

A single event handler can handle events from several different controls. For example, you may have a generic button click event handler that handles all the buttons on your form. The button that raised the event can be determined by testing the value of the sender parameter. In the following code snippet, a button click event handler casts the sender object (that is, the control that raised the event) to the Button type and then assigns the ID property of that button to a string variable.

 private void BtnClick(object sender, System.EventArgs e)     {        Button b = sender as Button;        String buttonID = b.ID;        switch (buttonID)        {           case "btnDoThis":              //  code to do this           case "btnDoThat":              //  code to do that        }        //  code to do stuff common to all the buttons     } 

This can eliminate a great deal of duplicate code and can make your program easier to read and maintain.



Programming ASP. NET
Programming ASP.NET 3.5
ISBN: 0596529562
EAN: 2147483647
Year: 2003
Pages: 173

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net