ASP 101 - Active Server Pages 101 - Web01
The Place ASP Developers Go!

Please visit our partners


Windows Technology Windows Technology
15 Seconds
4GuysFromRolla.com
ASP 101
ASP Wire
VB Forums
VB Wire
WinDrivers.com
internet.commerce internet.commerce
Partners & Affiliates














ASP 101 is an
internet.com site
ASP 101 is an internet.com site
IT
Developer
Internet News
Small Business
Personal Technology

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers

ASP 101 News Flash ASP 101 News Flash



 Top ASP 101 Stories Top ASP 101 Stories
The Top 10 ASP Links @ Microsoft.com
What is Adovbs.inc and Why Do I Need It?
An Overview of ASP.NET

QUICK TIP:
Use Option Strict
Show All Tips >>
ASP 101 RSS Feed ASP 101 Updates


Build Your Own ASP.NET 2.0 Web Site Using C# & VB, 2nd Edition

from SitePoint

Chapter 3: VB and C# Programming Basics

As you learned at the end of the last chapter, one of the great things about using ASP.NET is that we can pick and choose which of the various .NET languages we like. In this chapter, we'll look at the key programming principles that will underpin our use of Visual Basic and C#. We'll start by discussing some basic concepts of programming ASP.NET web applications using these two languages. We'll explore programming fundamentals such as variables, arrays, functions, operators, conditionals, loops, and events, and work through a quick introduction to object oriented programming (OOP). Next, we'll dive into namespaces and address the topic of classes--seeing how they're exposed through namespaces, and which ones you'll use most often.

The final sections of the chapter cover some of the ideas underlying modern, effective ASP.NET design, including code-behind and the value it provides by helping us separate code from presentation. We finish with an examination of how object oriented programming techniques impact the ASP.NET developer.

Programming Basics

One of the building blocks of an ASP.NET page is the application logic: the actual programming code that allows the page to function. To get anywhere with ASP.NET, you need to grasp the concept of events. All ASP.NET pages will contain controls such as text boxes, checkboxes, and lists. Each of these controls allows the user to interact with the application in some way: checking checkboxes, scrolling through lists, selecting list items, and so on. Whenever one of these actions is performed, the control will raise an event. It is by handling these events within our code that we get ASP.NET pages to do what we want.

For instance, imagine that a user clicks a button on an ASP.NET page. That button (or, more specifically, the ASP.NET Button control) raises an event (in this case, it will be the Click event). A method called an event handler executes automatically when an event is raised--in this case, the event handler code performs a specific action for that button. For instance, the Click event handler could save form data to a file, or retrieve requested information from a database. Events really are the key to ASP.NET programming, which is why we'll start this chapter by taking a closer look at them.

It wouldn't be practical, or even necessary, to cover all aspects of VB and C# in this book, so we're going to discuss enough to get you started, and complete this chapter's projects and samples using both languages. Moreover, we'd say that the programming concepts you'll learn here will be more than adequate to complete the great majority of day-to-day web development tasks using ASP.NET.

Control Events and Subroutines

As I just mentioned, an event (sometimes more than one) is raised, and handler code is called, in response to a specific action on a particular control. For instance, the code below creates a server-side button and label. Note the use of the OnClick attribute on the Button control. If you want to test the code, save the file in the Learning virtual directory you've been using for the other examples.

Example 3.1. ClickEvent.aspx (excerpt)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTMLXHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  
<html>
 <head>
   <title>Click the Button</title>
 </head>
 <body>
   <form runat="server">
     <asp:Button id="button" runat="server"
         OnClick="button_Click" Text="Click Me" />
     <asp:Label id="messageLabel" runat="server" />
   </form>
 </body>
</html>

When the button's clicked, it raises the Click event, and ASP.NET checks the button's OnClick attribute to find the name of the handler subroutine for that event. In the code above, we told ASP.NET to call the button_Click routine, so perhaps we'd better write this subroutine! We'd normally place it within a code declaration block inside the <head> tag, like this:

Example 3.2. ClickEvent.aspx (excerpt)

<head>
 <title>Click the Button</title>
 <script runat="server" language="VB">
   Public Sub button_Click(s As Object, e As EventArgs)
     messageLabel.Text = "Hello World"
   End Sub
 </script>
</head>

Example 3.3. ClickEvent.aspx (excerpt)

<head>
 <title>Click the Button</title>
 <script runat="server" language="C#">
   public void button_Click(Object s, EventArgs e)  
   {
     messageLabel.Text = "Hello World";
   }
 </script>
</head>

This code simply sets a message to display on the label that we declared with the button. So, when this page is run, and users click the button, they'll see the message "Hello World" appear next to it.

1556_0305_ClickEvent
Figure 3.1. Handling the Click event

Hopefully, you're starting to come to grips with the idea of control events, and the ways in which they're used to call particular subroutines. In fact, there are many events that your controls can use, though some of them are found only on certain controls. Here's the complete set of attributes that the Button control supports for handling events:

  • OnClick - As we've seen, the subroutine indicated by this attribute is called for the Click event, which occurs when the user clicks the button.
  • OnCommand - As with OnClick, the subroutine indicated by this attribute is called when the button is clicked.
  • OnLoad - The subroutine indicated by this attribute is called when the button is loaded for the first time--usually when the page first loads.
  • OnInit - When the button is initialized, any subroutine given in this attribute will be called.
  • OnPreRender - We can use this attribute to run code just before the button is rendered.
  • OnUnload - This subroutine will run when the control is unloaded from memory--basically, when the user goes to a different page or closes the browser entirely.
  • OnDisposed - The subroutine specified by this attribute is executed when the button is released from memory.
  • OnDataBinding - This attribute fires when the button is bound to a data source.

Don't worry too much about the intricacies of all these events and when they occur; I just want you to understand that a single control can produce a number of different events. In the case of the Button control, you'll almost always be interested in the Click event; the others are only useful in rather obscure circumstances.

When a control raises an event, the specified subroutine (if one is specified) is executed. Let's take a look at the structure of a typical subroutine that interacts with a web control:

Public Sub mySubName(s As Object, e As EventArgs)
 ' Write your code here
End Sub

public void mySubName(Object s, EventArgs e)  
{
 // Write your code here
}

Let's take a moment to break down all the components that make up a typical subroutine.

Public (Visual Basic), public (C#)

This command defines the scope of the subroutine. There are a few different options to choose from, the most frequently used being Public (for a global subroutine that can be used anywhere within the entire page) and Private (for subroutines that are available for the specific class only). (The C# equivalents of Public and Private are, perhaps predictably, public and private.) We'll analyze these options in more detail a bit later in the chapter.

Sub (Visual Basic), void (C#)

This command defines the chunk of code as a subroutine. A subroutine is a named block of code that doesn't return a result; thus, in C#, we use the void keyword, which means exactly what the name says. We don't need this in VB, though, because the Sub keyword implies that no value is returned.

mySubName(...)

This part gives the name we've chosen for the subroutine. The parameters and their data types are mentioned in the parentheses.

s As Object (Visual Basic), Object s (C#)

When we write a subroutine that will function as an event handler, it must accept two parameters. The first is a reference to the control that fired the event. Each control has a particular type, such as Label or TextBox, but Object is a generic type that can be used to reference any kind of object in .NET--even basic types, such as numbers or strings. Here, we're putting that Object in a variable named s (again, we'll talk more about variables later in this chapter). We can then use that variable to access features and settings of the specific control from our subroutine.

e As EventArgs (Visual Basic), EventArgs e (C#)

This, the second parameter, contains certain information that's specific to the event that was raised. Note that, in many cases, you won't need to use either of these two parameters, so you don't need to worry about them too much at this stage.

As this chapter progresses, you'll see how subroutines that are associated with particular events by the appropriate attributes on controls can revolutionize the way your user interacts with your application.

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.

Arrays

Arrays are a special variety of variable that's tailored for storing related items of the same data type. Any one item in an array can be accessed using the array's name, followed by that item's position in the array (its offset). Let's create a sample page to see how it's done. The results of this code are shown in Figure 3.3:

Example 3.6. Arrays.aspx

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  
<html>
 <head>
   <title>Arrays</title>
   <script runat="server" language="VB">
     Sub Page_Load()  
       ' Declare an array
       Dim drinkList(4) As String
       ' Place some items in it
       drinkList(0) = "Water"
       drinkList(1) = "Juice"
       drinkList(2) = "Soda"
       drinkList(3) = "Milk"
       ' Access an item in the array by its position
       drinkLabel.Text = drinkList(1)
     End Sub
   </script>
 </head>
 <body>
   <form runat="server">
     <asp:Label id="drinkLabel" runat="server" />
   </form>
 </body>
</html>

Example 3.7. Arrays.aspx

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
 <head>
   <title>Arrays</title>
   <script runat="server" language="C#">
     void Page_Load()  
     {
       // Declare an array
       string[] drinkList = new string[4];
       // Place some items in it
       drinkList[0] = "Water";
       drinkList[1] = "Juice";
       drinkList[2] = "Soda";
       drinkList[3] = "Milk";
       // Access an item in the array by its position
       drinkLabel.Text = drinkList[1];
     }
   </script>
 </head>
 <body>
   <form runat="server">
     <asp:Label id="drinkLabel" runat="server" />
   </form>
 </body>
</html>

1556_0315_Arrays
Figure 3.3. Reading an element from an array

There are some important points to pick up from this code. First, notice how we declare an array. In VB, it looks like a regular declaration for a string, except that the number of items we want the array to contain is provided in parentheses after the name:

Example 3.8. Arrays.aspx (excerpt)

Dim drinkList(4) As String

In C#, it's a little different. First, we declare that drinkList is an array by following the data type with two empty square brackets. We then specify that this is an array of four items, using the new keyword:

Example 3.9. Arrays.aspx (excerpt)

string[] drinkList = new string[4];

A crucial point to realize here is that, in both C# and VB, these arrays are known as zero-based arrays. In a zero-based array, the first item has position 0, the second has position 1, and so on through to the last item, which has a position that's one less than the size of the array (3, in this case). So, we specify each item in our array like this:

Example 3.10. Arrays.aspx (excerpt)

drinkList(0) = "Water"
drinkList(1) = "Juice"
drinkList(2) = "Soda"
drinkList(3) = "Milk"

Example 3.11. Arrays.aspx (excerpt)

drinkList[0] = "Water";
drinkList[1] = "Juice";
drinkList[2] = "Soda";
drinkList[3] = "Milk";

Note that C# uses square brackets for arrays, while VB uses standard parentheses. We have to remember that arrays are zero-based when we set the label text to the second item, as shown here:

Example 3.12. Arrays.aspx (excerpt)

drinkLabel.Text = drinkList(1)

Example 3.13. Arrays.aspx (excerpt)

drinkLabel.Text = drinkList[1];

To help this fact sink in, you might like to try changing this code to show the third item in the list, instead of the second. Can you work out what change you'd need to make? That's right--you need only to change the number in the brackets to reflect the new item's position in the array (don't forget to start at zero). In fact, it's this ability to select one item from a list using only its numerical location that makes arrays so useful in programming--we'll experience this first-hand as we get further into the book.

Functions

Functions are exactly the same as subroutines, but for one key difference: they return a value. In VB, we declare a function using the Function keyword in place of Sub, while in C#, we simply have to specify the return type in place of void. The following code shows a simple example:

Example 3.14. Functions.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>ASP.NET Functions</title>
   <script runat="server" language="VB">
     ' Here's our function  
     Function getName() As String
       Return "Zak Ruvalcaba"
     End Function
     ' And now we'll use it in the Page_Load handler
     Sub Page_Load(s As Object, e As EventArgs)  
       messageLabel.Text = getName()
     End Sub
   </script>
 </head>
 <body>
   <form runat="server">
     <asp:Label id="messageLabel" runat="server" />
   </form>
 </body>
</html>

Example 3.15. Functions.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>ASP.NET Functions</title>
   <script runat="server" language="C#">
     // Here's our function
     string getName()  
     {
       return "Zak Ruvalcaba";
     }
     // And now we'll use it in the Page_Load handler
     void Page_Load()  
     {
       messageLabel.Text = getName();
     }
   </script>
 </head>
 <body>
   <form runat="server">
     <asp:Label id="messageLabel" runat="server" />
   </form>
 </body>
</html>

When the page above is loaded in the browser, the Load event will be raised which will cause the Page_Load event handler to be called, which in turn will call the getName function. Figure 3.4 shows the result in the browser.

1556_0320_Functions
Figure 3.4. Executing an ASP.NET function

Here's what's happening: the line in our Page_Load subroutine calls our function, which returns a simple string that we can assign to our label. In this simple example, we're merely returning a fixed string, but the function could just as easily retrieve the name from a database (or somewhere else). The point is that, regardless of how the function gets its data, we call it in just the same way.

When we're declaring our function, we must remember to specify the correct return type. Take a look at the following code:

' Here's our function
Function addUp(x As Integer, y As Integer) As Integer
 Return x + y
End Function  
' And now we use it in Page_Load
Sub Page_Load(s As Object, e As EventArgs)  
 messageLabel.Text = addUp(5, 2).ToString()
End Sub

// Here's our function  
int addUp(int x, int y)  
{
 return x + y;
}
// And now we use it in Page_Load
void Page_Load()
{
 messageLabel.Text = addUp(5, 2).ToString();
}

You can easily adapt the previous example to use this new code so that you can see the results in your browser--just replace the code inside the <script> tags in Functions.aspx with the code above.

The first thing to notice in comparing this new code to the original version of Functions.aspx is that our function now accepts parameters. Any function or subroutine can take any number of parameters, of any type (there's no need for parameter types to match the return type--that's just coincidental in this example).

We can readily use the parameters inside the function or subroutine just by using the names we gave them in the function declaration (here, we've chosen x and y, but we could have chosen any names).

The other difference between this and the function declaration we had before is that we now declare our function with a return type of Integer or int, rather than String, because we want it to return a whole number.

When we call the new function, we simply have to specify the required number of parameters, and remember that the function will return a value with the type we specify. In this case, we have to convert the integer value that the function returns to a string, so that we can assign it to the label.

The simplest way to convert an integer to a string is to append .ToString() to the end of the variable name. In this case, we appended ToString on the function call which will return an integer during execution. Converting numbers to strings is a very common task in ASP.NET, so it's good to get a handle on it early.

Converting Numbers to Strings
There are more ways to convert numbers to strings in .NET, as the following lines of VB code illustrate:

messageLabel.Text = addUp(5, 2).ToString()
messageLabel.Text = Convert.ToString(addUp(5, 2))

If you prefer C#, these lines of code perform the same operations as the VB code above:

messageLabel.Text = addUp(5, 2).ToString();
messageLabel.Text = Convert.ToString(addUp(5, 2));

Don't be concerned if you're a little confused by how these conversions work, though--the syntax will become clear once we discuss object oriented concepts later in this chapter.

Operators

Throwing around values with variables and functions isn't of much use unless you can use them in some meaningful way, and to do so, we need operators. An operator is a symbol that has a certain meaning when it's applied to a value. Don't worry--operators are nowhere near as scary as they sound! In fact, in the last example, where our function added two numbers, we were using an operator: the addition operator, or + symbol. Most of the other operators are just as well known, although there are one or two that will probably be new to you. Table 3.2, outlines the operators that you'll use most often in your ASP.NET development.

Operators Abound!
The list of operators in Table 3.2 is far from complete. You can find detailed (though poorly written) lists of the differences between VB and C# operators on the Code Project web site.

Table 3.2. Common ASP.NET operators
1556_table32

The following code uses some of these operators:

If (user = "Zak" AndAlso itemsBought  <>  0) Then
 messageLabel.Text = "Hello Zak! Do you want to proceed to " & _
   "checkout?"
End If

if (user  ==  "Zak" && itemsBought  !=  0)  
{
 messageLabel.Text = "Hello Zak! Do you want to proceed to " +
   "checkout?";
}

Here, we use the equality, inequality (not equal to), and logical "and" operators in an If statement to print a tailored message for a given user when he has put a product in his electronic shopping cart. Of particular note is the C# equality operator, ==, which is used to compare two values to see if they're equal. Don't use a single equals sign in C# unless you're assigning a value to a variable; otherwise your code will have a very different meaning than you expect!

Breaking Long Lines of Code

Since the message string in the above example was too long to fit on one line in this book, we used the string concatenation operator to combine two shorter strings on separate lines to form the complete message. In VB, we also had to break one line of code into two using the line continuation symbol (_, an underscore at the end of the line to be continued). Since C# marks the end of each command with a semicolon (;), you can split a single command over two lines in this language without having to do anything special.

We'll use these techniques throughout this book to present long lines of code within a limited page width. Feel free to recombine the lines in your own code if you like--there's no length limit on lines of VB and C# code.

Conditional Logic

As you develop ASP.NET applications, there will be many instances in which you'll need to perform an action only if a certain condition is met, for instance, if the user has checked a certain checkbox, selected a certain item from a DropDownList control, or typed a certain string into a TextBox control. We check for such occurrences using conditionals, the simplest of which is probably the If statement. This statement is often used in conjunction with an Else statement, which specifies what should happen if the condition is not met. So, for instance, we may wish to check whether or not the name entered in a text box is Zak, redirecting the user to a welcome page if it is, or to an error page if it's not:

If (userName.Text = "Zak") Then  
 Response.Redirect("ZaksPage.aspx")
Else  
 Response.Redirect("ErrorPage.aspx")
End If

if (userName.Text == "Zak")  
{  
 Response.Redirect("ZaksPage.aspx");
}
else  
{
 Response.Redirect("ErrorPage.aspx");
}

Take Care with Case Sensitivity
Instructions are case-sensitive in both C# and VB, so be sure to use if in C# code, and If in VB code. On the other hand, variable and function names are case-sensitive only in C#. As such, in C# you could have two variables called x and X, which would be considered to be different; in VB, they would be considered to be the same variable.

Often, we want to check for many possibilities, and specify our application to perform a particular action in each case. To achieve this, we use the Select Case (VB) or switch (C#) construct:

Select Case userName
 Case "Zak"  
   Response.Redirect("ZaksPage.aspx")
 Case "Mark"  
   Response.Redirect("MarksPage.aspx")
 Case "Fred"  
   Response.Redirect("FredsPage.aspx")
 Case Else  
   Response.Redirect("ErrorPage.aspx")
End Select

switch (userName)  
{
 case "Zak":
   Response.Redirect("ZaksPage.aspx");
   break;
 case "Mark":
   Response.Redirect("MarksPage.aspx");
   break;
 case "Fred":
   Response.Redirect("FredsPage.aspx");
   break;
 default:
   Response.Redirect("ErrorPage.aspx");
   break;
}

Loops

As you've just seen, an If statement causes a code block to execute once if the value of its test expression is true. Loops, on the other hand, cause a code block to execute repeatedly for as long as the test expression remains true. There are two basic kinds of loop:

  • While loops, also called Do loops (which sounds like something Betty Boop might say!)
  • For loops, including For Next and For Each

A While loop is the simplest form of loop; it makes a block of code repeat for as long as a particular condition is true. Here's an example:

Example 3.16. Loops.aspx

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  
<html>
 <head>
   <title>Loops</title>
   <script runat="server" language="VB">
     Sub Page_Load(s As Object, e As EventArgs)
       ' Initialize counter
       Dim counter As Integer = 0
       ' Loop
       Do While counter <= 10
         ' Update the label
         messageLabel.Text = counter.ToString()
         ' We use the += operator to increase our variable by 1
         counter += 1
       Loop
     End Sub
   </script>
 </head>
 <body>
   <form runat="server">
     <asp:Label id="messageLabel" runat="server" />
   </form>
 </body>
</html>

Example 3.17. Loops.aspx

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  
<html>
 <head>
   <title>Loops</title>
   <script runat="server" language="C#">
     void Page_Load()
     {
       // initialize counter
       int counter = 0;
       // loop
       while (counter <= 10)  
       {
         // Update the label
         messageLabel.Text = counter.ToString();
         // C# has the ++ operator to increase a variable by 1
         counter++;
       }
     }
   </script>
 </head>
 <body>
   <form runat="server">
     <asp:Label id="messageLabel" runat="server"/>
   </form>
 </body>
</html>

If you load this page, you'll get the result illustrated in Figure 3.5.

1556_0325_Loops
Figure 3.5. Results of a While loop

When you open the page, the label will be set to show the number 0, then 1, then 2, all the way to 10. Of course, since all this happens in Page_Load (i.e. before any output is sent to the browser), you'll only see the last value assigned: 10.

This demonstrates that the loop repeats until the condition is no longer met. Try changing the code so that the counter variable is initialized to 20 instead of 0. When you open the page now, you won't see anything on the screen, because the loop condition was never met.

The other form of the While loop, called a Do While loop, checks whether or not the condition has been met at the end of the code block, rather than at the beginning:

Example 3.18. Loops.aspx (excerpt)

Sub Page_Load(s As Object, e As EventArgs)
 ' Initialize counter
 Dim counter As Integer = 0
 ' Loop
 Do  
   ' Update the label
   messageLabel.Text = counter.ToString()
   ' We use the += operator to increase our variable by 1
   counter += 1
 Loop While counter <= 10
End Sub

Example 3.19. Loops.aspx (excerpt)

void Page_Load()  
{
 // initialize counter
 int counter = 0;
 // loop
 do  
 {
   // Update the label
   messageLabel.Text = counter.ToString();
   // C# has the operator ++ to increase a variable by 1
   counter++;
 }
 while (counter <= 10);
}

If you run this code, you'll see it provides the exact same output we saw when we tested the condition before the code block. However, we can see the crucial difference if we change the code so that the counter variable is initialized to 20. In this case, we will, in fact, see 20 displayed, because the loop code is executed once before the condition is even checked! There are some instances when this is just what we want, so being able to place the condition at the end of the loop can be very handy.

A For loop is similar to a While loop, but we typically use it when we know beforehand how many times we need it to execute. The following example displays the count of items within a DropDownList control called productList:

Dim i As Integer
For i = 1 To productList.Items.Count
 messageLabel.Text = i.ToString()
Next

int i;
for (i = 1; i <= productList.Items.Count; i++)  
{
 messageLabel.Text = i.ToString();
}

In VB, the loop syntax specifies the starting and ending values for our counter variable within the For statement itself.

In C#, we assign a starting value (i = 1) along with a condition that will be tested each time we move through the loop (i <= productList.Items.Count), and identify how the counter variable should be incremented after each loop (i++). While this allows for some powerful variations on the theme in our C# code, it can be confusing at first. In VB, the syntax is considerably simpler, but it can be a bit limiting in exceptional cases.

The other type of For loop is For Each, which loops through every item within a collection. The following example loops through an array called arrayName:

For Each item In arrayName
 messageLabel.Text = item
Next

foreach (string item in arrayName)
{
 messageLabel.Text = item;
}

You may also come across instances in which you need to exit a loop prematurely. In these cases, you would use either Exit, if your code is in VB, or the equivalent (break) statement in C#, to terminate the loop:

Dim i As Integer
For i = 0 To 10
 If (i = 5) Then
   Response.Write("Oh no! Not the number 5!!")
   Exit For
 End If
Next

int i;
for (i = 0; i <= 10; i++)  
{
 if (i == 5)  
 {
   Response.Write("Oh no! Not the number 5!!");
   break;
 }
}

In this case, as soon as our For loop hits the condition i = 5, it displays a warning message using the Response.Write method (which will be familiar to those with past ASP experience), and exits the loop so that no further passes through the loop will be made.

Although we've only scratched the surface, VB and C# provide a great deal of power and flexibility to web developers, and time spent learning the basics now will more than pay off in the future.

Object Oriented Programming Concepts

VB and C# are modern programming languages that give you the tools to write structured, extensible, and maintainable code. The code can be separated into modules, each of which defines classes that can be imported and used in other modules. Both languages are relatively simple to get started with, yet they offer sophisticated features for writing complex, large-scale enterprise applications.

One of the reasons why these languages are so powerful is that they facilitate object oriented programming (OOP). In this section, we'll explain the fundamentals of OOP and learn how adopting good OOP style now can help you to develop better, more versatile web applications down the road. This section will provide a basic OOP foundation angled towards the web developer. In particular, we'll cover the following concepts:

  • objects
  • properties
  • methods
  • classes
  • scope
  • events
  • inheritance

In the pages that follow, we'll discuss these concepts briefly, and from Chapter 4 onwards, you'll see some practical examples of OOP in action.

Objects and Classes

So what does the term "object oriented programming" mean? Basically, as the name suggests, it's an approach to development that puts objects at the center of the programming model. The object is probably the most important concept in the world of OOP; an object is a self-contained entity that has state and behavior, just like a real-world object.

In programming, an object's state is described by its fields and properties, while its behavior is defined by its methods and events. An important part of OOP's strength comes from the natural way it allows programmers to conceive and design their applications.

We often use objects in our programs to describe real-world objects?we can have objects that represent a car, a customer, a document, or a person. Each object has its own state and behavior.

It's very important to have a clear understanding of the difference between a class and an object. A class acts like a blueprint for the object, while an object represents an instance of the class. I just said that you could have objects of type Car, for example. If you did, Car would be the class, or the type, and we could create as many Car objects as we wanted, calling them myCar, johnsCar, davesCar, and so on.

The class defines the behavior of all objects of that type. So all objects of type Car will have the same behavior--for example, the ability to change gear. However, each individual Car object may be in a different gear at any particular time; thus, each object has its own particular state.

Let's take another example: think of Integer (or int) as a class, and age and height as objects of type Integer. The class defines the behavior of the objects--they're numeric, and we can perform mathematical operations on them--and the instances of objects (age and height) have their behavior defined by the class to which they belong, but they also hold state (so age could be 20).

Take a look at the following code:

Dim age As Integer
Dim name As String
Dim myCar as Car
Dim myOtherCar as Car

int age;
string name;
Car myCar;
Car myOtherCar;

As you can see, the syntax for declaring an object is the same as that for declaring a simple integer or string variable. In C#, we first mention the type of the object, then we name that particular instance. In VB, we use the Dim keyword.

Object oriented programming sounds like an advanced topic, but getting started with it is actually very easy, because OOP offers us a natural way to conceive and design programs. Instead of writing long functions of code to perform specific tasks, OOP allows us to group pieces of related functionality into classes that we can reuse over and over, or even extend to incorporate new features. In OOP, one thinks of programming problems in terms of objects, properties, and methods. And, as we've seen, the best way to get a handle on these terms is to consider a real-world object and imagine how it might be represented in an OOP program. For the examples that follow, we'll use as our example my dog, an Australian Shepherd named Rayne.

Rayne is your average great big, friendly, loving, playful mutt. You might describe him in terms of his physical properties: he's gray, white, brown, and black, stands roughly one-and-a-half feet high, and is about three feet long. You might also describe some methods to make him do things: he sits when he hears the command "Sit," lies down when he hears the command "Lie down," and comes when his name is called.

So, if we were to represent Rayne in an OOP program, we'd probably start by creating a class called Dog. A class describes how certain types of objects look from a programming point of view. When we define a class, we must define the following two items:

  • Properties - Properties hold specific information relevant to that class of object. You can think of properties as characteristics of the objects that they represent. Our Dog class might have properties such as Color, Height, and Length.
  • Methods - Methods are actions that objects of the class can be told to perform. Methods are subroutines (if they don't return a value) or functions (if they do) that are specific to a given class. So the Dog class could have methods such as Sit and LieDown.

Once we've defined a class, we can write code that creates objects of that class, using the class a little like a template. This means that objects of a particular class expose (or make available) the methods and properties defined by that class. So, we might create an instance of our Dog class called rayne, set its properties accordingly, and use the methods defined by the class to interact with Rayne, as shown in Figure 3.6.

1556_fig-rayne
Figure 3.6. An instance of Dog

This is just a simple example to help you visualize what OOP is all about. In the next few sections, we'll cover properties and methods in greater detail, and talk about classes and class instances, scope, events, and inheritance.

Properties

As we've seen, properties are characteristics shared by all objects of a particular class. In the case of our example, the following properties might be used to describe any given dog:

  • color
  • height
  • length

In the same way, the more useful ASP.NET Button class exposes properties including:

  • Width
  • Height
  • ID
  • Text
  • ForeColor
  • BackColor

Unfortunately for me, if I get sick of Rayne's color, I can't change it in real life. However, if Rayne was a .NET object, we could change any of his properties in the same way that we set variables (although a property can be read-only or write-only). For instance, we could make him brown very easily:

rayne.Color = "Brown"

rayne.Color = "Brown";

In this example, we're using an instance of our Dog class called rayne. We use the dot operator (.) to access the property Color that the object exposes and set it to the string "Brown".

Methods

With our dog example, we can make a particular dog do things by calling commands. If I want Rayne to sit, I tell him to sit. If I want Rayne to lie down, I tell him to lie down. In object oriented terms, I tell him what I want him to do by calling a predefined command or method, and an action results. For example, to make Rayne sit, we would use the following code to call his Sit method:

rayne.Sit()

rayne.Sit();

Given that rayne is an instance of our Dog class, we say that the Sit method is exposed by the Dog class.

Classes

You can think of a class as a template for building as many objects of a particular type as you like. When you create an instance of a class, you are creating an object of that class, and the new object has all the characteristics and behaviors (properties and methods) defined by the class.

In our dog example, rayne was an instance of the Dog class, as Figure 3.6 illustrated. In our code, we'd create a new instance of the Dog class called rayne, as shown below:

Dim rayne As New Dog()

Dog rayne = new Dog();

Constructors

Constructors are special kinds of method are that used to initialize the object. In OOP, when we create new instances of a class, we say we're instantiating that class. The constructor is a method of a class that's executed automatically when a class is instantiated.

At least one constructor will be defined for most of the classes you will write (though we can define more than one constructor for a class, as we'll see shortly), since it's likely that some data will need to be initialized for each class at creation time.

In C# and VB, the constructor is defined as a method that has the same name as the class, and has no return type.

Scope

You should now understand programming objects to be entities that exist in a program and are manipulated through the methods and properties they expose. However, in some cases, we want to create for use inside our class methods that are not available to code outside that class.

Imagine we're writing the Sit method inside this class, and we realize that before the dog can sit, it has to shuffle its back paws forward a little (bear with me on this one!). We could create a method called ShufflePaws, then call that method from inside the Sit method. However, we don't want code in an ASP.NET page or in some other class to call this method--it'd just be silly. We can prevent it by controlling the scope of the ShufflePaws method.

Carefully controlling which members of a class are accessible from outside that class is fundamental to the success of object oriented programming. You can control the visibility of a class member using a special set of keywords called access modifiers:

  • Public - Defining a property or method of a class as public allows that property or method to be called from outside the class itself. In other words, if an instance of this class is created inside another object (remember, too, that ASP.NET pages themselves are objects), public methods and properties are freely available to the code that created that instance of the class. This is the default scope for VB and C# classes.
  • Private - If a property or method of a class is private, it cannot be used from outside the class itself. So, if an instance of this class is created inside an object of a different class, the creating object has no access to private methods or properties of the created object.
  • Protected - A protected property or method sits somewhere between public and private. A protected member is accessible from the code within its class, or to the classes derived from it. We'll learn more about derived classes a bit later.

Deciding which access modifier to use for a given class member can be a very difficult decision--it affects not only your class, but also the other classes and programs that use your class. Of special importance are the class's public members, which together form the class's public interface. The public interface acts like a contract between your class and the users of your class, and if it's designed properly, it shouldn't change over time. If, for example, you mark the Sit method as public, and later decide to make it private, all the other classes that use this method will have to change accordingly, which is not good. For an extreme scenario, imagine that in a year, Microsoft decided to remove the ToString method from its classes--obviously, this would wreak havoc with your code.

Keep Everything Private until you Need It
As a simple guideline for designing your classes, remember that it's often easier just to make all the members private, and make public only those that really need to be public. It's much easier to add to a public interface than it is to remove from it.

Events

We've covered events in some depth already. To sum up, events occur when a control object sends a message as a result of some change that has been made to it. Generally, these changes occur as the result of user interaction with the control via the browser. For instance, when a button is clicked, a Click event is raised, and we can handle that event to perform some action. The object that triggers the event is referred to as the event sender, while the object that receives the event is referred to as the event receiver. You'll learn more about these objects in Chapter 4.

Understanding Inheritance

The term inheritance refers to the ability of a specialized class to refine the properties and methods exposed by another, more generalized class.

In our dog example, we created a class called Dog, then created instances of that class to represent individual dogs such as Rayne. However, dogs are types of animals, and many characteristics of dogs are shared by all (or most) animals. For instance, Rayne has four legs, two ears, one nose, two eyes, etc. It might be better, then, for us to create a base class called Animal. When we then defined the Dog class, it would inherit from the Animal class, and all public properties and methods of Animal would be available to instances of the Dog class.

Similarly, we could create a new class based on the Dog class. In programming circles, this is called deriving a subclass from Dog. For instance, we might create a class called AustralianShepherd, and one for my other dog, Amigo, called Chihuahua, both of which would inherit the properties and methods of the Dog base class, and define new classes specific to each breed.

Don't worry too much if this is still a little unclear. The best way to appreciate inheritance is to see it used in a real program. The most obvious use of inheritance in ASP.NET is in the technique called code-behind, and we'll build plenty of examples using inheritance and code-behind in Chapter 4, Constructing ASP.NET Web Pages.

Objects In .NET

If this is the first book in which you've read about object oriented programming, you've probably started to dream about objects! Don't worry, the effect of first exposure to objects doesn't usually last for more than a week. Even though this is yet another discussion about objects, I promise it won't be boring. Moreover, in the course of this section, we'll cover some important concepts that every serious .NET programmer must know.

So far, we've explored various concepts that apply in one form or the other to almost any truly object oriented language. Every language has its peculiarities, but the general concepts are the same in all of these languages.

You may already have heard the common mantra of object oriented programmers: "everything is an object." This has two meanings. First of all, in C#, every program consists of a class. In all stages of application development, from design to implementation, decisions must be made in regard to the way we design and relate objects and classes to each other. Yes, objects are everywhere.

.NET extends this to yet another level, giving the phrase "everything is an object" extra meaning. In the world of .NET, every class ultimately derives from a base class named Object, so "everything is an object" becomes "everything is an Object."

If you look at the documentation for the ASP.NET Page class, you can see the list of classes from which this class inherits, as shown in Figure 3.7.

1556_fig-pagehierarchy
Figure 3.7. The Page class's documentation

You'll remember from the last section that we said our hypothetical AustralianShepherd class would inherit from the more general Dog class, which, in turn, would inherit from the even more general Animal class. This is exactly the kind of relationship that's being shown in Figure 3.7?Page inherits methods and properties from the TemplateControl class, which in turn inherits from a more general class called Control. In the same way that we say that an Australian Shepherd is an Animal, we say that a Page is a Control. Control, like all .NET classes, inherits from Object.

Since Object is so important that every other class derives from it, either directly or indirectly, it deserves a closer look. Object contains the basic functionality that the designers of .NET felt should be available in any object. The Object class contains these public members:

  • Equals
  • ReferenceEquals
  • GetHashCode
  • GetType
  • ToString

The only member we're really interested in at this moment is ToString, which returns the text representation of an object. This method is called automatically when conversions to string are needed, as is the case in the following code, which joins a number and a string:

Dim age As Integer = 5
Dim message As String = "Current Age: " & age

int age = 5;
string message = "Current Age: " + age;

Namespaces

As ASP.NET is part of the .NET Framework, we have access to all the goodies that are built into it in the form of the .NET Framework Class Library. This library represents a huge resource of tools and features in the form of classes; these classes are organized in a hierarchy of namespaces. When we want to use certain features that .NET provides, we have only to find the namespace that contains the desired functionality, and import that namespace into our ASP.NET page. Once we've done that, we can make use of the .NET classes in that namespace to achieve our own ends.

For instance, if we wanted to access a database from a page, we would import the namespace that contains classes for this purpose, which could be System.Data.SqlClient. You can view the namespace of a class when visiting its page in the .NET documentation. For example, the Button control's class can be found in System.Web.UI.WebControls.

To use a class that's part of a namespace that isn't available to you by default, you either need to import the namespace, or reference the class using its fully qualified name, such as System.Web.UI.WebControls. To import a namespace page, we use the Imports directive in VB, and using in C#:

Imports System.Data.SqlClient

using System.Data.SqlClient;

As we've imported that namespace, we have access to all the classes that it contains.

Using Code-behind Files

Most companies that employ web development teams usually split projects into two groups--visual design and functional development--because software engineers are usually poor designers, and designers are often poor engineers. Until now, our ASP.NET pages have contained code render blocks that place VB or C# code directly into the ASP.NET page. The problem with this approach is that there's no separation between the presentational elements of the page and the application logic. Traditional ASP was infamous for creating "spaghetti" code, which was scattered and intertwined throughout the presentation elements. This made it very tricky to manage the code between development teams, as you'll know if you've ever tried to pick apart someone else's ASP code. In response to these problems, ASP.NET introduced a new development approach that allows code developers to work separately from the presentation designers who lay out individual pages.

This new method, called code-behind, keeps all of your presentational elements (controls) inside the .aspx file, but moves all of your code to a separate class in a .vb or .cs code-behind file. Consider the following ASP.NET page, which displays a simple button and label:

Example 3.20. Hello.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>Sample Page using VB</title>
   <script runat="server" language="VB">
     Sub Click(s As Object, e As EventArgs)
       messageLabel.Text = "Hello World"
     End Sub
   </script>
 </head>
 <body>
   <form runat="server">
     <asp:Button id="submitButton" Text="Click Me"
         runat="server" OnClick="Click" />
     <asp:Label id="messageLabel" runat="server" />
   </form>
 </body>
</html>

Example 3.21. Hello.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>Sample Page using C#</title>
   <script runat="server" language="C#">
     void Click(Object s, EventArgs e)  
     {
       messageLabel.Text = "Hello World";
     }
   </script>
 </head>
 <body>
   <form runat="server">
     <asp:Button id="submitButton" Text="Click Me"  
          runat="server" OnClick="Click" />
     <asp:Label id="messageLabel" runat="server" />
   </form>
 </body>
</html>

Let's see how this example could be separated into the following distinct files:

HelloCodeBehind.aspx

   layout, presentation, and static content
HelloCodeBehind.vb or HelloCodeBehind.cs

   code-behind files containing a custom page class

First, we take all the code and place it in the code-behind file (HelloCodeBehind.vb or HelloCodeBehind.cs). This file is a pure code file, and contains no HTML or other markup tags. Nevertheless, we can still access presentation elements from this file, using their IDs (such as messageLabel) as shown below:

Example 3.22. HelloCodeBehind.vb

' First off we import some useful namespaces
Imports System
Imports System.Web.UI
Imports System.Web.UI.WebControls
' The partial class
Public Partial Class HelloCodeBehind
 Inherits System.Web.UI.Page
 ' Here's the Click handler just as it appeared before
 Sub Click(s As Object, e As EventArgs)
   messageLabel.Text = "Hello World"
 End Sub
End Class

Example 3.23. HelloCodeBehind.cs

// First off we import some useful namespaces
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
// The partial class
public partial class HelloCodeBehind: System.Web.UI.Page  
{
 // Here's the Click handler just as it appeared before
 public void Click(Object s, EventArgs e)  
 {
   messageLabel.Text = "Hello World";
 }
}

Without code, the main ASP.NET page becomes a bit simpler:

Example 3.24. HelloCodeBehind.aspx

<%@ Page Language="VB" CodeFile="HelloCodeBehind.vb"
   Inherits="HelloCodeBehind"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
 <head>
   <title>Sample Page Code Behind Demo using VB</title>
 </head>
 <body>
   <form runat="server">
     <asp:Button id="submitButton" Text="Click Me"  
         runat="server" OnClick="Click" />
     <asp:Label id="messageLabel" runat="server" />
   </form>
 </body>
</html>

Example 3.25. HelloCodeBehind.aspx

<%@ Page Language="C#" CodeFile="HelloCodeBehind.cs"
   Inherits="HelloCodeBehind"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
 <head>
   <title>Sample Page Code Behind Demo using C#</title>
 </head>
 <body>
   <form runat="server">
     <asp:Button id="submitButton" Text="Click Me"  
         runat="server" OnClick="Click" />
     <asp:Label id="messageLabel" runat="server" />
   </form>
 </body>
</html>

As you can see, the only line that differs between these .aspx pages is the Page directive. Since the .aspx pages now contain only HTML layout, the contents are identical no matter what language you use for the code.

Partial Classes
If you have programmed with ASP.NET 1.1, you may already have noticed the changes in the code-behind model. In ASP.NET 2.0, the code-behind file is cleaner and smaller--a feat it achieves by using a new feature of VB and C# called partial classes. Read on for the details!

The code-behind file is written differently from what you've seen so far. While we no longer need <script> tags, we find a class definition in their place. As the VB example shows, we start with three lines that import namespaces for use within the code:

Example 3.26. HelloCodeBehind.vb (excerpt)

Imports System
Imports System.Web.UI
Imports System.Web.UI.WebControls

The next lines create a new class, named HelloCodeBehind. Since our code-behind page contains code for an ASP.NET page, our class inherits from the Page class:

Example 3.27. HelloCodeBehind.vb (excerpt)

Public Partial Class HelloCodeBehindSample
 Inherits System.Web.UI.Page

This is the practical application of inheritance that we mentioned earlier. The HelloCodeBehind class inherits from Page, borrowing all its functionality, and extending it according to the particular needs of the page.

But what does Partial mean? A new feature in .NET 2.0, partial classes allow a class to be spread over multiple files. ASP.NET 2.0 uses this feature to make programmers' lives easier. We write one part of the class in the code-behind file, and ASP.NET generates the other part of the class for us, adding the object declarations for all the user interface elements.

Take a look at the Click subroutine, though which we access the messageLabel object without defining it anywhere in the code:

Example 3.28. HelloCodeBehind.vb (excerpt)

Sub Click(s As Object, e As EventArgs)
 messageLabel.Text = "Hello World"
End Sub

That's pretty handy! However, don't be fooled into thinking that you can use objects that haven't been declared--the messageLabel object has been declared in another partial class file that the ASP.NET runtime generates for us. The file contains declarations for all the controls referenced in HelloCodeBehind.aspx.

As I hope you can see, code-behind files are easy to work with, and they can make managing and using our pages much more straightforward than keeping your code in code declaration blocks. You'll find yourself using code-behind files in most of the real-world projects that you build, but for simplicity's sake, we'll stick with code declaration blocks for one more chapter.

Summary

Phew! We've covered quite a few concepts over the course of this chapter. Don't worry--with a little practice, these concepts will become second nature to you. I hope you leave this chapter with a basic understanding of programming concepts as they relate to the ASP.NET web developer.

The next chapter will begin to put all the concepts that we've covered so far into practice. We'll begin by working with HTML Controls, Web Forms, and Web Controls, before launching into our first hands-on project!


Excerpted from the book "Build Your Own ASP.NET 2.0 Web Site Using C# & VB, 2nd Edition". Learn to create ASP.NET Web sites from scratch using freely available software. Copyright 2006 SitePoint Pty Ltd.


Build Your Own ASP.NET 2.0 Web Site Using C# & VB, 2nd Edition


Home |  News |  Samples |  Articles |  Lessons |  Resources |  Forum |  Links |  Search |  Feedback

Internet.com
The Network for Technology Professionals

Search:

About Internet.com

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | E-mail Offers