Build Your Own ASP.NET Website Using C# and VB.NET. Pt. 3. | 6

Build Your Own ASP.NET Website Using C# and VB.NET. Pt. 3.

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 a resulting action is performed. In VB.NET or C#, we would write this as rayne.Sit(), or rayne.LieDown().

As Web developers, we frequently call methods when a given event occurs. For instance, the example earlier in this chapter that took information from an Access database created an object called objConn to represent the connection to the database. We then opened the connection by calling the Open() method on that object as follows:

Dim objConn As As New OleDbConnection(
  "Provider=Microsoft.Jet.OLEDB.4.0;" & _
  "Data Source=C:\Database\books.mdb")
…
objConn.Open()

We say that the Open() method is exposed by the connection object, and that we’re calling the Open() method on the OleDbConnection object stored in objConn. We don’t need to know what dark secrets the method uses to do its magic; all we need to know is its name and what we use it for.

You can think of a class as a template for building as many objects as you like of a particular type. 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 shown in Figure 3.4.

We see that Rayne is an object of class Dog. In our code, we could create a new instance of the Dog class, call it rayne, and use all the properties and methods exposed by the object.

In OOP, when we create new instances of a class, we say we’re instantiating that class. For instance (no pun intended!), if we need to programmatically create a new instance of the Button control class, we could write the following code:

Dim myButton As New Button()
Button myButton = new Button();

As you can see, we’ve essentially created a new object called myButton from the Button class. We can then access the properties and methods that the Button exposes through our new instance:

myButton.Text = "Click Me!"
myButton.Text = "Click Me!";

You should now have a concept of programming objects as entities that exist in a program and are manipulated through the methods and properties they expose. However, in some cases, we want to create methods to use inside our class, which are not available when that class is used in code. Let’s return to the Dog class to illustrate.

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 (Just 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 this by controlling the scope of that method.

The two types of scope available in VB.NET and C# that you should know about are:

The term inheritance refers to the ability for one class to use properties and methods exposed by another class.

In our dog example, we first 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 define 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 for Australian Shepherd 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 ones 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 comes with the technique of code-behind.

Most companies that employ 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.NET or C# code directly within the ASP.NET page. The problem with this approach is that there is 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 introduces a new way of developing pages that allows code developers to work separately from the presentational 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 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:

<html>
<head>
  <title>Sample Page using VB.NET</title>
  <script runat="server" language="VB">
    Sub Click(s As Object, e As EventArgs)
      lblMessage.Text = "Hello World"
    End Sub
  </script>
</head>
<body>
  <form runat="server">
    <asp:Button id="btnSubmit" Text="Click Me" runat="server"
      OnClick="Click" />
    <br /><br /><asp:Label id="lblMessage" runat="server" />
  </form>
</body>
</html>
<html>
<head>
  <title>Sample Page using C#</title>
  <script runat="server" language="C#">
    void Click(Object s, EventArgs e) {
      lblMessage.Text = "Hello World";
    }
  </script>
</head>
<body>
  <form runat="server">
    <asp:Button id="btnSubmit" Text="Click Me" runat="server"
      OnClick="Click" />
    <br /><br /><asp:Label id="lblMessage" runat="server" />
  </form>
</body>
</html>

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

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

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

As you can see, the only line that’s different between the .aspx pages is the Page directive:

The only real change between the VB.NET and C# versions of the page is the source filename extension. In both cases, the page inherits from the class Sample.

The code-behind file is written differently from what you’re used to seeing so far. While we no longer need <script> tags, we find a class definition in its place. Looking at the VB.NET example, we start with three lines that import namespaces to be used in the code:

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

This is the practical application of inheritance that I mentioned above. Instead of using the built-in Page class, the code-behind method has you derive a subclass of Page for each page in your site. Next, we have to declare the controls that we want to use from the .aspx page—if we forget this step, we won’t be able to access them from our code:

Finally, we create the Click subroutine just as before, and terminate the class:

As I hope you can see, code-behind files are reasonably easy to work with, and they can make managing and using our pages much more straightforward. On a typical project, I tend to use code-behind files quite frequently, but for simplicity’s sake, we’ll stick with code declaration blocks for at least the next few chapters.



[3] Strictly speaking, a page is simply another type of control, and so page events are actually control events. When you’re first coming to grips with ASP.NET, however, it can help to think of them differently, especially since you don’t usually use OnEventName attributes to assign subroutines to handle them.

Created: March 27, 2003
Revised: June 18, 2004

URL: http://webreference.com/programming/asp_net3/1