Article

ASP.NET 2.0: A Getting Started Guide

Page: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 Next

Page Events

Until now, we've considered only events that are raised by controls. However, there is another type of event: the page event. Technically, a page is simply another type of control, so page events are a particular kind of control event.

The idea is the same as for control events, except that here, it is the page as a whole that generates the events. (Strictly speaking, a page is simply another type of control, so page events are actually control events. But when you're first learning ASP.NET, it can be helpful to think of page events as being different, especially since you don't usually use OnEventName attributes to assign subroutines to handle them.) You've already used one of these events: the Page_Load event, which is fired when the page loads for the first time. Note that we don't need to associate handlers for page events as we did for control events; instead, we just place our handler code inside a subroutine with a preset name.

The following list outlines the most frequently used page event subroutines:

  • Page_Init - called when the page is about to be initialized with its basic settings
  • Page_Load - called once the browser request has been processed, and all of the controls in the page have their updated values
  • Page_PreRender - called once all objects have reacted to the browser request and any resulting events, but before any response has been sent to the browser
  • Page_UnLoad - called when the page is no longer needed by the server, and is ready to be discarded

The order in which the events are listed above is also the order in which they're executed. In other words, the Page_Init event is the first event raised by the page, followed by Page_Load, Page_PreRender, and finally Page_UnLoad.

The best way to illustrate how these events work is through an example. Create the following PageEvents.aspx file in the Learning virtual directory:

Example 3.4. PageEvents.aspx (excerpt)        
       
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"        
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">        
<html>        
 <head>        
   <title>Page Events</title>        
   <script runat="server" language="VB">        
     Sub Page_Init(s As Object, e As EventArgs)        
       messageLabel.Text = "1. Page_Init <br/>"        
     End Sub        
     Sub Page_Load(s As Object, e As EventArgs)        
       messageLabel.Text += "2. Page_Load <br/>"        
     End Sub        
     Sub Page_PreRender(s As Object, e As EventArgs)        
       messageLabel.Text += "3. Page_PreRender <br/>"        
     End Sub        
     Sub Page_UnLoad(s As Object, e As EventArgs)        
       messageLabel.Text += "4. Page_UnLoad <br/>"        
     End Sub        
   </script>        
 </head>        
 <body>        
   <form runat="server">        
     <asp:Label id="messageLabel" runat="server" />        
   </form>        
 </body>        
</html>

Example 3.5. PageEvents.aspx (excerpt)        
       
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"        
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">        
<html>        
 <head>        
   <title>Page Events</title>        
   <script runat="server" language="C#">        
     void Page_Init(Object s, EventArgs e)        
     {        
       messageLabel.Text = "1. Page_Init <br/>";        
     }        
     void Page_Load(Object s, EventArgs e)        
     {        
       messageLabel.Text += "2. Page_Load <br/>";        
     }        
     void Page_PreRender(Object s, EventArgs e)        
     {        
       messageLabel.Text += "3. Page_PreRender <br/>";        
     }        
     void Page_UnLoad(Object s, EventArgs e)        
     {        
       messageLabel.Text += "4. Page_UnLoad <br/>";        
     }        
   </script>        
 </head>        
 <body>        
   <form runat="server">        
     <asp:Label id="messageLabel" runat="server" />        
   </form>        
 </body>        
</html>

You can see that the event handlers (the functions that are executed to handle the events) aren't specifically defined anywhere. There's no need to define them, because these events are generated by default by the ASP.NET page, and their handlers have the default names that we've used in the code (Page_Init, Page_Load, etc.). As the page loads, it will generate a number of events. Within each event's event handler, we've added a message to the Label control; this will give us visual proof that the events actually fire in order. No matter which version of the code you execute (C# or VB), the output should look like Figure 3.2.

1556_0310_PageEvents
Figure 3.2. Handling ASP.NET events

As you can see, Page_UnLoad doesn't generate any output. This is because, at that point, the HTML output has already been generated and sent to the browser.

Popular Page_Load
The event you'll make the most use of in your code is Page_Load. However, in certain situations the other events will be helpful as well. It's also worth noting that ASP.NET supports other events, which we haven't covered here. You'll only need those in certain, complex applications that aren't in the scope of this book.

Variables and Variable Declaration

Variables are fundamental to programming, and you're almost certain to have come across the term before. Basically, variables let you give a name, or identifier, to a specific piece of data; we can then use that identifier to store, modify, and retrieve the data in question.

VB and C# have access to the same basic data types, which are defined as foundation classes of the .NET Framework. However, they can be named differently, as each language defines its own aliases. There are many different kinds of data types, including strings, integers (whole numbers), and floating point numbers (fractions or decimals). Before you can use a variable in VB or C#, you must specify the types of data it can contain, using keywords such as String, Integer, and Decimal, like this:

Dim name As String        
Dim age As Integer        
       
string name;        
int age;

These lines declare the type of data we want our variables to store, and are therefore known as "variable declarations." In VB, we use the keyword Dim, which stands for "dimension," while in C#, we simply precede the variable name with the appropriate data type.

Sometimes, we want to set an initial value for variables that we declare; we can do this using a process known as initialization:

Dim carType As String = "BMW"        
       
string carType = "BMW";

We can also declare and/or initialize a group of variables of the same type simultaneously. This practice isn't recommended, though, as it makes the code more difficult to read.

Dim carType As String, carColor As String = "blue"        
       
string carType, carColor = "blue";

Table 3.1 lists the most useful data types available in VB and C#.

Table 3.1. A list of commonly used data types
1556_table31

You'll encounter many other data types as you progress, but this list provides an overview of the ones you'll use most often.

Many Aliases are Available
These data types are the VB- and C#-specific aliases for types of the .NET Framework. For example, instead of Integer or int, you could use System.Int32 in any .NET language; likewise, instead of Boolean or bool, you could use System.Boolean, and so on.

To sum up, once you've declared a variable as a given type, it can only hold data of that type: you can't put a string into an integer variable, for instance. However, there are frequently times when you'll need to convert one data type to another. Have a look at this code:

Dim intX As Integer        
Dim strY As String = "35"        
intX = strY + 6        
       
int intX;        
string strY = "35";        
intX = strY + 6;

Now, you or I might think that this could make sense--after all, the string strY contains a number, so we might wish to add it to another number. Well, this isn't so simple for a computer!

VB performs some conversions for us. The VB version of the code will execute without a hitch, because the string will be converted to a number before the mathematical operation is applied. C#, on the other hand, will throw an error, as it's more strict than VB about conversions.

As a rule of thumb, it's better to stay on the safe side and avoid mixing types wherever possible.

VB and C#--Strongly Typed Languages
Even though their behavior is a little bit different, both VB and C# are strongly typed languages. Strongly typed languages are those that are very strict about data types. Many other languages--mostly scripting languages such as JavaScript--are loosely typed, which means that they're more flexible when it comes to dealing with data types. For example, if you try to sum a number with a string, as we did in the previous code snippet, the JavaScript interpreter would make the conversion for you automatically. At times, despite being a strongly typed language at heart, VB does a bit of background work for you, which makes it slightly easier to work with.

In .NET, you can (and sometimes need to) explicitly convert, or cast, the string into an integer before you're able to sum them up:

Dim intX As Integer        
Dim strY As String = "35"        
intX = Int32.Parse(strY) + 6        
       
int intX;        
string strY = "35";        
intX = Convert.ToInt32(strY) + 6;

Now, the computer will accept even with the C# code, because it ends up adding two numbers, rather than a number and a string, as we tried initially. This principle holds true whenever we're mixing types in a single expression.

If you liked this article, share the love:
Print-Friendly Version Suggest an Article

Sponsored Links