BUY THIS BOOK

Safari Books Online

What is this?

Looking to Reprint this content?


Programming ASP.NET
Programming ASP.NET, Second Edition

By Jesse Liberty, Dan Hurwitz

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: ASP.NET and the .NET Framework
Microsoft first announced ASP.NET (then called ASP+) and the .NET platform in July, 2000. In essence, .NET is a new development framework that provides a fresh application programming interface to the services and APIs of classic Windows operating systems, especially Windows 2000, Windows XP, and the recently released Windows Server 2003, while bringing together a number of disparate technologies that emerged from Microsoft during the late 1990s. Among the latter are COM+ component services, a commitment to XML and object-oriented design, support for new web services protocols such as SOAP, WSDL, and UDDI, and a focus on the Internet.
ASP.NET is significant enhancement to and extension of classic Microsoft ASP. ASP programmers will be very pleased by how easy the transition to ASP.NET is, yet there is tremendous power and flexibility in the new development platform. ASP and ASP.NET applications can run side by side, allowing for easy migration of legacy applications.
This chapter introduces both ASP.NET and the .NET platform, notably the .NET Framework.
The .NET Framework sits on top of the operating system, which can be any flavor of Windows, and consists of a number of components. Currently, the .NET Framework consists of:
  • Five official languages (C#, Visual Basic .NET, Managed C++, and J#, as well as the JScript .NET scripting language)
  • A number of related class libraries, collectively known as the Framework Class Library (FCL)
  • The Common Language Runtime (CLR), an object-oriented platform for Windows and web development that all these languages share
  • The .NET Framework is an integral part of Windows Server 2003 but must be downloaded and installed to run on Windows 2000 or Windows XP. Earlier versions of Windows are not supported.
Figure 1-1 breaks down the .NET Framework into its architectural components.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The .NET Framework
The .NET Framework sits on top of the operating system, which can be any flavor of Windows, and consists of a number of components. Currently, the .NET Framework consists of:
  • Five official languages (C#, Visual Basic .NET, Managed C++, and J#, as well as the JScript .NET scripting language)
  • A number of related class libraries, collectively known as the Framework Class Library (FCL)
  • The Common Language Runtime (CLR), an object-oriented platform for Windows and web development that all these languages share
  • The .NET Framework is an integral part of Windows Server 2003 but must be downloaded and installed to run on Windows 2000 or Windows XP. Earlier versions of Windows are not supported.
Figure 1-1 breaks down the .NET Framework into its architectural components.
Figure 1-1: NET Framework architecture
The Common Language Runtime (CLR) executes your program on your web server. The CLR activates objects, performs security checks on them, lays them out in memory, executes them, and handles garbage collection.
In Figure 1-1, the layer on top of the CLR is a set of framework base classes, followed by an additional layer of data and XML classes, plus another layer of classes intended for web services and Web Forms, and Windows forms. Collectively, these classes are known as the Framework Class Library (FCL). With more than 5,000 classes, the FCL facilitates rapid development of ASP.NET applications. This same class library is used for desktop applications as well.
Microsoft .NET supports a Common Language Specification (CLS) that allows you to choose the syntax with which you are most comfortable. You can write classes in C# and derive from them in VB.NET. You can throw an exception in VB.NET and catch it in a C# class. Suddenly the choice of language is a personal preference rather than a limiting factor in your application's development.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
ASP.NET
ASP.NET is the name Microsoft has given to the combination of its two web development technologies: Web Forms and web services. Using ASP.NET, it is easier than ever to create web applications that are dynamic and data-driven, that scale well, and that work well across a broad range of browsers without any custom coding by the developer.
Used in conjunction with Visual Studio .NET, Web Forms allow you to apply Rapid Application Development techniques to building web applications. Simply drag and drop controls onto your form, double-click on a control, and write the code to respond to the associated event.
Generally speaking, web services are web applications without a user interface that allow you to provide services to other web sites or applications. As you'll see in later chapters, ASP.NET allows you to create web services using a simple text editor or facilitate the process by using Visual Studio .NET.
The key differences between ASP.NET and ASP are:
  • ASP.NET is much more event-driven, with the event handlers running on the server.
  • ASP.NET separates code from HTML.
  • The code in ASP.NET is compiled, not interpreted.
  • Configuration and deployment are greatly simplified.
There are many other minor differences, but these four are the key changes, and they change everything. The event-driven model in ASP.NET is very powerful and is explored in detail in Chapter 3. The separation of HTML from code, and the fact that the code is compiled rather than interpreted, allows for the creation of larger, easier-to-scale, easier-to-maintain web sites. The configuration and deployment simplifications make working with ASP.NET web sites, both large and small, much easier.
You can program ASP.NET in any language that supports the .NET CLS. This book provides examples in both C# and VB.NET. It is a theme of this book that C# and VB.NET are sufficiently similar, at least as used in ASP.NET, so if you know one you will have no problem with examples shown in the other. That said, we do offer the examples in both languages to simplify the process of learning the technology.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Hello World
It is a long-standing tradition among programmers to begin the study of a new language by writing a program that prints "Hello World" to the screen. In deference to tradition, our first web page will do just that.
The tool you are most likely to use when developing ASP.NET applications is an integrated development environment (IDE), such as Visual Studio .NET. However, you may use any editor you like—even the venerable text editor Notepad.
There are a number of advantages to using an IDE such as Visual Studio .NET. The Visual Studio .NET editor provides indentation and color coding of your source code, the IntelliSense feature helps you choose the right commands and attributes, and the integrated debugger helps you find and fix errors in your code.
The disadvantage of using an IDE, however, is that it may do so much work for you that you don't get a good feel for what is going on in your application. It is like bringing your car in to the mechanic. He does all the work for you, but you never really learn how your engine works.
As a beginner, you may be better off doing more of the work yourself, giving up the support of the IDE in exchange for the opportunity to see how things really work. In this chapter, you will use a simple text editor to create the source code for the first several iterations. At the end of the chapter, you will use Visual Studio .NET to create the same web page. (For the remainder of the book, you will find both examples that are created using a text editor and examples that are developed in Visual Studio .NET.)
Back in the old days, before ASP and ASP.NET, web pages were created with simple HTML. To better appreciate the features of ASP.NET, you will first create the Hello World web page in HTML, then convert it to ASP, and finally convert it to ASP.NET.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Visual Studio .NET
If your goal is to produce significant, robust, and elegant applications with few bugs, in a minimum amount of time, then a modern IDE, such as Microsoft Visual Studio .NET, is an invaluable tool. Visual Studio .NET offers many advantages to the .NET developer, including:
  • A modern interface, using a tabbed document metaphor for code and layout screens, and dockable toolbars and information windows.
  • Convenient access to multiple design and code windows.
  • WYSIWYG (What You See Is What You Get) visual design of Windows and Web Forms.
  • Code completion, which allows you to enter code with fewer errors and less typing.
  • Intellisense, which pops up help on every method and function call as you type, providing the types of all parameters and the return type.
  • Dynamic, context-sensitive help, which allows you to view topics and samples relevant to the code you are writing at the moment. You can also search the complete SDK library from within the IDE.
  • Immediate flagging of syntax errors, which allows you to fix problems as they are entered.
  • A Start Page, which provides easy access to new and existing projects.
  • The same code editor for all .NET languages, which shortens the learning curve. Each language can have specialized aspects, but all languages benefit from shared features, such as incremental search, code outlining, collapsing text, line numbering, color-coded keywords, etc.
  • An HTML editor, which provides both Design and HTML views that update each other in real time.
  • A Solution Explorer, which displays all the files comprising your solution (which is a collection of projects) in an outline.
  • A Server Explorer, which allows you to log on to servers to which you have network access, access the data and services on those servers, and perform a variety of other chores.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Start Page
When you open Visual Studio .NET for the first time (unless you configure it otherwise), you'll find yourself looking at the Visual Studio .NET application window, as shown in Figure 2-1.
Figure 2-1: Visual Studio .NET Start Page with Online Resource tab displayed
Along the top of the application window is a fairly typical collection of Windows menu items and buttons, plus several that are specific to the Visual Studio .NET integrated development environment. Specialized tabs that provide access to tools and controls, and to other servers and databases in the development environment, appear to the left of the application window, labeled Toolbox and Server Explorer, respectively. Additional windows for exploring the files and classes associated with a particular project and for accessing help, appear on the righthand side. More windows are available through the Visual Studio .NET menu bar (see Section 2.3).
At the center of the application window is the Start Page, which contain three tabs, one for creating new projects or opening existing ones (the Projects tab), another for locating online resources, such as code samples, community sites or available web services (the Online Resources tab), and a third for creating a profile to personalize your development environment (the My Profile tab).
As shown in Figure 2-1, the lefthand side of the Online Resource tab contains links to a variety of MSDN and other resources available over the Internet. These include:
Get Started
Allows you to search for code samples related to your project.
What's New
Links to new developments in the .NET world, training and events, and tips.
Online Community
Links to the .NET community, including web sites, newsgroups, tech support resources, code examples, and component sources.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Projects and Solutions
A typical .NET application is comprised of many items: source files, assembly information files, references, icons, as well as miscellaneous other files and folders. Visual Studio .NET organizes these items into a container called a project. One or more projects are contained within a solution. When you create a new project, Visual Studio .NET automatically creates the containing solution.
Solutions typically contain one or more projects. They may contain other, independent items as well. These independent solution items are not specific to any particular project, but apply, or scope, to the entire solution. The solution items are not an integral part of the application, because they can be removed without changing the compiled output. They can be managed with source control.
Miscellaneous files are independent of the solution or project, but they may be useful to have handy. They are not included in any build or compile, but will display in the Solution Explorer (described in the section "View Menu," later in this chapter), and may be edited there. Typical miscellaneous files include project notes, database schemas, or sample code files.
It is also possible to have a solution that does not contain any projects—just solution or miscellaneous files, which can be edited using Visual Studio .NET.
Solutions are defined within a file named for the solution with a .sln extension. The .sln file contains a list of the projects that comprise the solution, the location of any solution-scoped items, and any solution-scoped build configurations. Visual Studio .NET also creates a .suo file with the same name as the .sln file (e.g., mySolution.sln and mySolution.suo). The .suo file contains data used to customize the IDE on a per-user and per-solution basis.
You can open a solution by double-clicking the .sln file in Windows Explorer. If the .sln file is missing, then that solution must be created again from scratch by adding projects into the solution. On the other hand, if the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Integrated Development Environment (IDE)
The Visual Studio .NET integrated development environment (IDE) consists of windows for visual design of forms, code-editing windows, menus and toolbars providing access to commands and features, toolboxes containing controls for use on the forms, and windows providing properties and information about forms, controls, projects, and the solution.
Visual Studio .NET is a multiple document interface (MDI) application. It consists of a single parent window, which contains multiple windows. All the menus, toolbars, design and editing windows, and miscellaneous other windows are associated with the single parent window.
A typical layout of the IDE is shown in Figure 2-3. This section discusses the overall layout and many of the features that make working with the IDE so productive.
Figure 2-3: Typical IDE layout
The Visual Studio .NET window has a title bar across the top with menus below. Under the menus are toolbars with buttons that duplicate many of the common menu commands. Nearly everything that can be done through menus can also be done with context-sensitive pop-up menus, as described in the discussion that follows. The menu and toolbars are easily customized by clicking on Tools Customize.
The toolbars are docked along the top of the window by default. As with many Windows applications, they can be undocked and moved to other locations, either free-floating or docked along other window edges. You move the toolbars by grabbing them with the mouse and dragging them where you want.
Figure 2-3 shows a design view of a web form, with the design window occupying the main area in the center of the screen. This allows for visual design by dragging and dropping components from the Toolbox along the left side of the screen.
Along the right side of the screen are two windows, both of which will be covered in more detail later in this chapter. The upper window is the Solution Explorer. Below that is the Properties window. There are many other similar windows available to you, as will be described.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Building and Running
You can run your application at any time by selecting either Start or Start Without Debugging from the Debug menu, or you can accomplish the same results by pressing either F5 or Ctrl+F5, respectively. In addition, you can start the program by clicking the Start icon ( ) on the Standard toolbar.
The program can be built (i.e., .exe and .dll files generated) by selecting a command under the Build menu. You have the option of building the entire solution or only the currently selected project. For a full discussion of application deployment, please see Chapter 20.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Events
Chapter 1 provided just a glimpse of ASP.NET. Now you might be asking yourself (especially if you're a developer experienced in classic ASP), "What's the big deal?" One of the significant differences between ASP.NET and classic ASP is that ASP.NET is event-driven.
To talk about events, you must understand controls. To talk about controls, you must first know about events. We'll solve this classic chicken-and-the-egg problem by providing just enough information in this chapter about controls to understand events. The next two chapters will discuss controls in depth.
The two models of program execution (which are not necessarily mutually exclusive) are linear and event-driven.
Linear programs move in a linear fashion, 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 function or subroutine calls) may redirect the flow of the program, but essentially, once program execution begins, it runs its course unaffected by anything the user or system may do. Prior to the advent of GUI environments, most computer programs were linear.
In contrast, event-driven programming responds to events. An event is generated (or raised) when "something happens," such as the user pressing a button. Often, events are generated by user action, but events can also be generated by the system starting or finishing work. 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.
Windows is an event-driven program. The operating system is relatively quiescent until it detects an event such as the user clicking the mouse on a button. The click raises an event, which must be handled. The method that responds to the event is called the event handler . When the event is raised, the event handler, if one exists, is automatically executed by Windows.
In ASP.NET, objects may raise events and may have assigned event handlers. For example, a button may raise the Click event and may have an OnClick method that handles the event.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Event Model
The two models of program execution (which are not necessarily mutually exclusive) are linear and event-driven.
Linear programs move in a linear fashion, 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 function or subroutine calls) may redirect the flow of the program, but essentially, once program execution begins, it runs its course unaffected by anything the user or system may do. Prior to the advent of GUI environments, most computer programs were linear.
In contrast, event-driven programming responds to events. An event is generated (or raised) when "something happens," such as the user pressing a button. Often, events are generated by user action, but events can also be generated by the system starting or finishing work. 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.
Windows is an event-driven program. The operating system is relatively quiescent until it detects an event such as the user clicking the mouse on a button. The click raises an event, which must be handled. The method that responds to the event is called the event handler . When the event is raised, the event handler, if one exists, is automatically executed by Windows.
In ASP.NET, objects may raise events and may have assigned event handlers. For example, a button may raise the Click event and may have an OnClick method that handles the event.
The event handler name is formed by prepending the word "On" to the event name, so in the case of a Click event, the event handler is called OnClick. Table 3-1 lists some of the more commonly used events and the names of their event handlers.
Table 3-1: Common events and their event handler names
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
ASP Versus ASP.NET Events
ASP was primarily a linear programming model. It had six events, of which only four were commonly used. These were:
  • Application_OnStart, which was fired when the application started
  • Application_OnEnd, which was fired when the application terminated
  • Session_OnStart, which was fired at the beginning of each session
  • Session_OnEnd, which was raised when the session ended
ASP.NET, on the other hand, is primarily an event-driven programming model. The application has events, each session has events, and the page and most of the server controls can also raise events. All ASP.NET events are handled on the server. Some events cause an immediate posting to the server, while other events are simply 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 occur on the client. In ASP.NET applications, however, an event is typically raised on the client, but handled on the server.
Consider a classic ASP web page with a button control on it. A Click event is raised when the button is clicked. This event is handled by the client (that is, the browser), which responds by posting the form to the server. No event handling occurs server-side.
Now consider an ASP.NET web page with a similar button control. The difference between an ASP.NET button control and a classic HTML button control is primarily that 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 also transmitted to the server. The server determines if the Click event has an event handler associated with it, and, if so, the event handler is executed on the server.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Event Arguments
Events are handled by delegates. Essentially, a delegate is an object that encapsulates the description of a method to which you may delegate responsibility for handling the event.
For a complete discussion of delegates, see Programming C#, Third Edition, by Jesse Liberty (O'Reilly).
Event handlers must always take two parameters and return nothing (in VB.NET, use a Sub, in C# return void). The first parameter represents the object raising the event. The second, called the event argument, contains information specific to the event, if any. For most events, the event argument is of type EventArgs, which does not expose any properties. So, the general prototype for an event in Visual Basic is:
Private Sub EventName(ByVal sender As Object, _
                      ByVal e As EventArgs)
The general prototype for an event in C# is:
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. Chapter 5 details the specifics of the event argument for each control.
Note that when using Visual Studio .NET, the IDE often inserts qualifying namespaces in front of parameter types in event handler declarations. These are redundant, as long as the relevant namespace is already referenced in the project using a using statement in C# or an Imports statement in VB.NET. For example, the default Page_Load event handler in VB.NET inserted by Visual Studio .NET looks like:
Private Sub Page_Load(ByVal sender As System.Object, _
                      ByVal e As System.EventArgs) Handles MyBase.Load
The following declaration works equally as well, since the System namespace is automatically imported into ASP.NET applications:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Application and Session Events
ASP.NET supports the Application and Session events familiar to ASP programmers. An Application_Start event is raised when the application first 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. Note that garbage collection will automatically take care of freeing up memory, but if you allocated unmanaged resources, such as components created with languages that are not compliant 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 specific to the session, such as opening a database connection. When the session ends, there will be a Session_End event.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Page and Control Events
The page and controls all have a number of events that are derived from the Control class (or the TemplateControl class, in the case of the Error event). All pass an event argument of type EventArgs that exposes no properties. Some of these events are listed in Table 3-2.
Table 3-2: Some common page and control events
Event name
Description
DataBinding
Occurs when control binds to a data source
Disposed
Occurs when 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. Chapter 9 provides a complete description of controls and data binding.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
IsPostBack
The page exposes the IsPostBack property. This is a read-only Boolean property that indicates if the page or control is being loaded for the first time, or if it is being loaded in response to a client postback. Many expensive operations (such as getting data from a database or populating ListItems) must be performed only the first time the page or control is loaded. If the page is posted to the server and then reloaded, there is no need to repeat the operation. By testing the value of IsPostBack, you can skip the expensive operation, as in the code snippets in Example 3-1 and Example 3-2.
Example 3-1. Testing for IsPostBack in VB.NET
sub Page_Load(ByVal Sender as Object, _
              ByVal e as EventArgs)
   if not IsPostBack then
      '  Do the expensive operations only the 
      '  first time the page is loaded.
   end if
end sub
Example 3-2. Testing for IsPostBack in C#
               void Page_Load(Object sender, EventArgs e)
{
   if (! IsPostBack)
   {
      //  Do the expensive operations only the 
      //  first time the page is loaded.
   }
}
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
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) 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-3 summarizes the controls with postback and non-postback events.
Table 3-3: Controls with postback and non-postback events
Postback
Non-postback
Button
CheckBox
Calendar
CheckBoxList
DataGrid
DropDownList
DataList
ListBox
ImageButton
RadioButtonList
LinkButton
RadioButton
Repeater
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Comparing ASP.NET to ASP
Classic ASP is not event driven in the way that ASP.NET is. To see the difference, consider the following application: you want to open the NorthWind database, supplied with both Microsoft SQL Server and Microsoft Access, and read through the Customers table. For each customer, you want to display the company name, customer ID, the name and title of the contact person, and the phone number. If the contact person is the owner, you want to display the title in red so that it is easy to see.
This example contains a great deal of complexity that will be covered in future chapters, including all the issues surrounding database access, but the fundamentals are straightforward. In classic ASP you would open a connection to the database, perform a query, and get back a RecordSet. You then iterate over the RecordSet, adding each record to an HTML table. If the current record's ContactTitle column is "Owner," you set the display to red. The code to accomplish this in classic ASP is shown in Example 3-3.
Example 3-3. Populating a table in classic ASP
<% Response.Expires=0 %>
<HTML>
<HEAD>
<META NAME="GENERATOR" Content="Microsoft FrontPage 4.0">
<META HTTP-EQUIV="Content-Type" content="text/html; charset=iso-8859-1">
<TITLE>List Log</TITLE>
<STYLE>
BODY,TD, TH {font-family:Verdana;font-size:8pt}
.controls {font-family:Verdana;font-size:8pt}
#owner {color:red}
</STYLE>
</HEAD>
<BODY>
<%   

   dim DBConn, rs
   set DBConn = Server.CreateObject("ADODB.Connection")

   DBConn.open "Driver={SQL Server};server=YourServer; uid=sa; pwd=YourPw;
                 database=northwind;"
   
   set rs = DBConn.Execute("select * from Customers")
   
%>
   <table bgcolor = "lavender">
      <tr>
         <th>Company Name</th>
         <th>Customer ID</th>
         <th>Contact</th>
         <th>Title</th>
         <th>Phone</th>
      </tr>
   <% while not rs.eof %>
      <tr bgColor="lightsteelblue">
         <td><% =rs("CompanyName") %></td>
         <td><% =rs("CustomerID") %> </td>
         <td><%=rs("ContactName") %></td>
         <td 
            <% if rs("ContactTitle") = "Owner" then %>
            id = owner
            <% end if %>
            > <% = rs("ContactTitle") %> </td>
         <td><%=rs("Phone") %></td>
      </tr>

   <% 
      rs.moveNext
       wend 
   %>
   </Table>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Events in Visual Studio .NET
The Visual Studio .NET 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 and 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. You have already seen some of these capabilities in this chapter, as well as the "manual" way of implementing events. In this section, you will see even easier ways to create event handlers in Visual Studio .NET.
Although events are handled in essentially the same way in C# and VB.NET under the hood, the syntax used by the two languages is very different. You can see this in the boilerplate created by Visual Studio .NET.
When a new web application is created in Visual Studio .NET, it automatically includes a code skeleton for the Page_Load event handler. A completed event handler was shown in Example 3-4 using VB .NET and in Example 3-5 using C#.
The event handler declaration in VB .NET has the form:
Private Sub Page_Load(ByVal sender As System.Object, _
                      ByVal e As System.EventArgs) _
                      Handles MyBase.Load
The Handles keyword indicates that this event handler method will handle the Load event of the base class.
In C#, the event handler declaration has the following syntax:
private void Page_Load(Object sender, System.EventArgs e)
{
Notice that there is no indication as to which event this method will handle. That connection is made in the block of code inside the region labeled Web Form Designer generated code. Expanding that region reveals a method called InitializeComponent, which is called from within the OnInit event handler. Inside the InitializeComponent method is the following line of code:
this.Load += new System.EventHandler(this.Page_Load);
This line adds the Page_Load method to the Load delegate, causing the method to be invoked every time that event is raised.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: Controls
Controls are the building blocks of a graphical user interface (GUI). Familiar controls include buttons, checkboxes, list boxes, and so forth. Controls can provide a means for a user to indicate a preference, enter data, or make selections.
There are five types of web controls (each but the first will be covered in detail in this and coming chapters). They are:
HTML controls
The original controls available to any HTML page. These all work in ASP.NET exactly as they work in other web pages. HTML controls will be used where appropriate in this book, but will not be discussed in detail. For a good resource on HTML controls, see HTML: The Definitive Guide, Second Edition, by Chuck Musciano and Bill Kennedy (O'Reilly).
HTML server controls
Based on original HTML controls, but enhanced to enable server-side processing.
Web (ASP) server controls
Server-side controls providing the same functionality as HTML server controls but integrated into the ASP.NET programming model.
Validation controls
Provide a full range of built-in form validation capability. Chapter 8 discusses validation controls.
User controls and custom controls
Controls created by the developer. Chapter 14 discusses user and custom controls.
HTML server controls and ASP controls both offer significant improvements over the old-style HTML controls. These include:
  • The ability to automatically maintain state, discussed in detail in Chapter 6.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
HTML Server Controls
Normal HTML controls such as <h1>, <a>, and <input> are not processed by the server, but are sent directly to the browser for display. Standard HTML controls can be exposed to the server and made available for server-side processing by turning them into HTML server controls. Server-side processing allows for data binding, programmatic response to events, and the ability to use a fully featured and compiled coding language rather than a scripting language.
To convert an HTML control to an HTML server control, simply add the attribute runat="server". In addition, you will probably want to add an id attribute, so that contents of the control can be accessed and controlled programmatically. For example, start with a simple input control:
<input type="text" size="40">
You can convert it to an HTML server control by adding the id and runat attributes, as follows:
<input type="text" id="BookTitle" size="40" runat="server">
There are several benefits to converting an HTML control to an HTML server control:
  • Once a control is converted to a server control, it can be referred to in code. For example, in Example 4-1 and Example 4-2 you can read or set the value of the text box by referring to lblBookName.Value or txtBookName.Value.
  • Server controls retain state during round trips to the server (more on this in Chapter 6).
  • Server controls generate events, which your code can then handle.
  • Server controls are aware of the client browser level and generate HTML appropriate to the target browser.
Example 4-1 and Example 4-2 demonstrate the use of HTML server controls in C# and VB.NET, respectively. In these listings, a text box is used to prompt the user to enter a book name. When the Button control is clicked, it fires an event that fills a second text box with the contents of the first text box and also changes its size.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
ASP (Web Server) Controls
The third type of control is the ASP control , also known as the ASP server control or the web server control . In this book, we will refer to it as an ASP control, since the syntax used to implement it is of the form:
<asp:controlType
      id="ControlID"
      runat="server" />
Here, the control tag always begins with asp:. ASP controls offer a more consistent programming model than the analogous HTML server control. For example, in HTML, the input tag (<input>) is used for buttons, single-line text fields, checkboxes, hidden fields, and passwords. For multiline text fields, you must use the <textarea> tag. With ASP controls, each different type of functionality corresponds to a specific control. For example, all text is entered using the TextBox control; the number of lines is specified using a property. In fact, for ASP controls in general, all the attributes correspond to properties of the control.
The ASP controls also include additional, rich controls, such as the Calendar and AdRotator.
Example 4-5 and Example 4-6 demonstrate the use of ASP controls in a web page analogous to the HTML server controls of Example 4-1 and Example 4-2. They show the use of the TextBox and Button ASP controls, rather than of the HTML controls.
Example 4-5. Code listing for csASPServerControls1.aspx
<%@ Page Language="C#" %>
<html>

<script runat="server">
   void btnBookName_Click(Object Source, EventArgs E)
   {
      lblBookName.Text = txtBookName.Text;
   }
</script>

   <body>
   <form runat="server">

      <h1>ASP Controls</h1>

      <br/>
      <h2>The date and time is <% =DateTime.Now.ToString(  ) %>.</h2>

      <br/>

      <h2>ASP Control</h2>
      Book Name:&nbsp;&nbsp;&nbsp;
      <asp:TextBox 
               id="txtBookName" 
         text="Enter book name."
         runat="server"
             width="250px" />

      <br/>
      <br/>
      <br/>

      <asp:Button
               id="btnBookName" 
         
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 5: ASP Control Details
Chapter 4 briefly discussed the different types of controls available in ASP.NET. It went into some detail on HTML server controls and gave an introductory example of ASP server controls. While the latter are sometimes also referred to as web server controls, in the context of this book we call them, simply, ASP controls to reflect the syntax used to implement them:
<asp:controlType
      id="ControlID"
      runat="server" />
Notice that the control tag always begins with asp:.
This chapter provides a wealth of detail about ASP controls. It discusses the features and properties common to many of these controls and surveys the specific details of all the ASP controls included with the .NET Framework.
In this section, you will create a simple web page, in either C# or VB.NET, in which you will explore many of the properties, events, and methods common to all ASP controls. Example 5-1 shows csASPServerControlBasics1.aspx, the first iteration in C#, and Example 5-2 shows vbASPServerControlBasics1.aspx, the equivalent file in VB.NET. These two examples demonstrate a Label control, an event handler, and properties being set for a control.
Example 5-1. Basic web page in C#, csASPServerControlBasics1.aspx
<%@ Page Language="C#" %>
<script runat="server">
   void lblTime_Init(Object Source, EventArgs E)
   {
      lblTime.Font.Name = "Verdana";
      lblTime.Font.Size = 20;
      lblTime.Font.Underline = true;
      lblTime.Font.Bold = true;
      lblTime.Font.Italic = true;
      lblTime.Font.Overline = true;
      lblTime.Font.Strikeout = true;
      lblTime.Text = DateTime.Now.ToString(  )  
         + ". Font Name: "
         + lblTime.Font.Name;
   }
</script>

<html>
   <body>
   <form runat="server">

      <h1>ASP Controls</h1>
      <h2>Basics 1</h2>

      <asp:label
         id="lblTime"
         onInit="lblTime_Init"
         runat="server" />
   </form>
   </body>
</html>
Example 5-2. Basic web page in VB.NET, vbASPServerControlBasics1.aspx
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Basics
In this section, you will create a simple web page, in either C# or VB.NET, in which you will explore many of the properties, events, and methods common to all ASP controls. Example 5-1 shows csASPServerControlBasics1.aspx, the first iteration in C#, and Example 5-2 shows vbASPServerControlBasics1.aspx, the equivalent file in VB.NET. These two examples demonstrate a Label control, an event handler, and properties being set for a control.
Example 5-1. Basic web page in C#, csASPServerControlBasics1.aspx
<%@ Page Language="C#" %>
<script runat="server">
   void lblTime_Init(Object Source, EventArgs E)
   {
      lblTime.Font.Name = "Verdana";
      lblTime.Font.Size = 20;
      lblTime.Font.Underline = true;
      lblTime.Font.Bold = true;
      lblTime.Font.Italic = true;
      lblTime.Font.Overline = true;
      lblTime.Font.Strikeout = true;
      lblTime.Text = DateTime.Now.ToString(  )  
         + ". Font Name: "
         + lblTime.Font.Name;
   }
</script>

<html>
   <body>
   <form runat="server">

      <h1>ASP Controls</h1>
      <h2>Basics 1</h2>

      <asp:label
         id="lblTime"
         onInit="lblTime_Init"
         runat="server" />
   </form>
   </body>
</html>
Example 5-2. Basic web page in VB.NET, vbASPServerControlBasics1.aspx
<%@ Page Language="VB" %>
<script runat="server">
   Sub lblTime_Init(ByVal Sender as Object, _
                    ByVal e as EventArgs)
      lblTime.Font.Name = "Verdana"
      lblTime.Font.Size = new FontUnit(20)
      lblTime.Font.Underline = true
      lblTime.Font.Bold = true
      lblTime.Font.Italic = true
      lblTime.Font.Overline = true
      lblTime.Font.Strikeout = true
      lblTime.Text = DateTime.Now(  ) _
         & ". Font Name: " _
         & lblTime.Font.Name
   End Sub
</script>

<html>
   <body>
   <form runat="server">

      <h1>ASP Controls</h1>
      <h2>Basics 1</h2>

      <asp:label
         id="lblTime"
         onInit="lblTime_Init"
         runat="server" />
   </form>
   </body>
</html>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Label Control
A Label control is used to display text. The Label control's Text property contains the text string to be displayed. Note that Text is the only Label control property that is not inherited from the WebControl class. The Label control has no events or methods that are not derived from WebControl.
You have already seen the Label control used in the previous code examples in this chapter. The Text and Font properties of the Label control can be set programmatically (as shown in Example 5-1 and Example 5-2) or declaratively (as demonstrated in Example 5-3 and Example 5-4).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
TextBox Control
The TextBox control can be used for both user input and read-only text display. It can be configured to be any one of the following: single-line, multiline, or to accept passwords. If multiline, it automatically wraps, unless the Wrap property is set to false. The text it contains can exceed the length of the control displayed on the page.
Table 5-2 lists many of the common properties specific to the TextBox control. If any of these attributes are omitted from the control, then the default value will apply.
Table 5-2: Some properties specific to the TextBox control
Name
Type
Get
Set
Values
Description
AutoPostBack
Boolean
x
x
true, false
Determines if automatic postback to server will occur if user changes contents of control. If false, postback to server will not occur until the page is posted, either by a button or another control with AutoPostBack set to true. Default is false.
Columns
Int32
x
x
0, 1, 2, and so on
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Button Controls
Buttons are controls that post the form back to the server, enabling server-side processing to commence. There are three types of button controls:
Button
LinkButton
ImageButton
In addition to the properties, methods, and events inherited along with all the other ASP controls, all three button types have the following two events:
Click
Raised when control is clicked and no command name is associated with the button (that is, no value has been assigned to the Button control's CommandName property). The method is passed an argument of type EventArgs.
Command
Raised when the control is clicked and a command name is associated with the button (that is, a command name has been assigned to the Button control's CommandName property). The event is passed an argument of type CommandEventArgs, which has the following two members:
CommandName
The name of the command
CommandArgument
An optional argument for the command
The code in Example 5-5 and Example 5-6 creates a web page containing three buttons, one of each type. Each button performs the same task: transferring control to another web page. Example 5-5 shows the C# code, and Example 5-6 shows the same code in VB.NET.
In order for the code in Example 5-5 and Example 5-6 to work correctly, you must have a target web page to link to. This can be any valid .htm, .asp or
Additional content appear