BUY THIS BOOK

Safari Books Online

What is this?

Looking to Reprint this content?


Programming ASP .NET
Programming ASP .NET By Jesse Liberty, Dan Hurwitz
February 2002
Pages: 960

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. .NET is, in essence, a new development framework that provides a fresh application programming interface to the services and APIs of classic Windows operating systems, especially Windows 2000, 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, all integrated within the DNA architecture.
ASP.NET represents a significant enhancement to and extension of classic 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:
  • Four official languages: C#, Visual Basic .NET, Managed C++, and JScript .NET.
  • The Common Language Runtime (CLR), an object-oriented platform for Windows and web development that all these languages share.
  • A number of related class libraries, collectively known as the Framework Class Library (FCL).
Figure 1-1 breaks down the .NET Framework into its system architectural components.
Figure 1-1: .NET Framework architecture
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:
  • Four official languages: C#, Visual Basic .NET, Managed C++, and JScript .NET.
  • The Common Language Runtime (CLR), an object-oriented platform for Windows and web development that all these languages share.
  • A number of related class libraries, collectively known as the Framework Class Library (FCL).
Figure 1-1 breaks down the .NET Framework into its system 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 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 faciliate 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 Common Language Specification. The examples in this book will be given 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!
Chapter 2: Hello World
The previous chapter introduced the ASP.NET architecture. In future chapters, you will learn all about creating web applications with ASP.NET. The current chapter presents a whirlwind tour by creating a simple web page to show you how easy it can be.
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. You may use any editor you like, however -- 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!
The HTML Version
Straight HTML provides a means of creating and presenting static web pages. This book is not a tutorial on how to write HTML, and we assume you know enough HTML to follow the simple examples provided. (For background reading, see HTML: The Definitive Guide ,by Chuck Musciano and Bill Kennedy, published by O'Reilly.) To get started, create a very simple Hello World HTML file, as shown in Example 2-1, and call it HelloWorld1.htm. The output is shown in Figure 2-1.
Example 2-1. Code listing for HelloWorld1.htm
<html>
   <body>

      <h1>Hello World</h1>

   </body>
</html>
Figure 2-1: Output from Example 2-1
The HTML page displays the static text, using the HTML heading1 format. If you want to include dynamic content, such as the results of a query against a database, or even the current time, then a static HTML page is not the thing to use. For that you need some sort of server processing. There are a number of alternatives; we will focus on ASP and then on 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!
The ASP Version
ASP allows the programmer to intersperse scripting code snippets within the HTML code. This scripting code can be written in a scripting language such as JavaScript or VBScript. Adding embedded script to your sample web page allows you to insert dynamic content. Modify the previous code listing, converting it to ASP, by changing the filename extension to .asp and adding VBScript to display the current time, as shown in Example 2-2. The output is shown in Figure 2-2.
Example 2-2. Code listing for HelloWorld1.asp
<html>
   <body>

      <h1>Hello World</h1>
      <br/>
      <h2>The date and time is <% =Now%>.</h2>

   </body>
</html>
Figure 2-2: Output from Example 2-2
It may not look like much, but this represents a vast improvement over static HTML. ASP allows you to create web sites full of rich and dynamic content. The scripting allows for queries, reads and writes against databases, implementation of programming logic, control of the appearance of web pages in response to user actions or returned data, and a host of other features.
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 the ASP.NET Way
You willcomplete this evolutionary journey by changing your Hello World web page from ASP to ASP.NET. A key difference in ASP.NET is that you no longer use interpreted languages but instead use compiled languages. Typically, ASP.NET applications are built using either C# or VB.NET. In either case, the performance will be a great improvement over script.
A significant theme of this book is that the choice between C# and VB.NET is purely syntactic; you can express any ASP.NET programming idea in either language. We suggest you write in whichever language you're more comfortable with. The transition from VBScript to VB.NET may be slightly easier than to C#, but much of the Microsoft and third-party documentation is in C#. In this book we will show most examples in both languages, though we confess to a slight preference for C# because it is a bit more terse.
For a full exploration of VB.NET, see Programming Visual Basic .NET , by Dave Grundgeiger (O'Reilly), and for C#, see Programming C#, by Jesse Liberty (O'Reilly).
Example 2-3 shows vbHelloWorld1.aspx in VB.NET, and Example 2-4 shows the same program in C#.
Example 2-3. Code listing for vbHelloWorld1.aspx
<%@ Page Language="VB" %>
<html>
   <body>

      <h1>Hello World</h1>
      <h1>ASP.NET Style</h1>
      <h2>Using VB .NET</h2>

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

   </body>
</html>
Example 2-4. Code listing for csHelloWorld1.aspx
<%@ Page Language="C#" %>
<html>
   <body>

      <h1>Hello World</h1>
      <h1>ASP.NET Style</h1>
      <h2>Using C#</h2>

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

   </body>
</html>
Note that the changes required to convert the ASP page to ASP.NET are minimal:
  1. Rename the file, changing the extension from
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 Using Visual Studio .NET
Visual Studio .NET is a full-featured IDE that provides all sorts of productivity tools for developing .NET applications, both for the Windows desktop and for the Web. These features include:
  • A Start page, which allows you to set user preferences for IDE behavior and provides easy access to new and existing projects.
  • Dynamic, context-sensitive help, which allows you to view topics and samples relevant to your current selection. You can also search the MSDN library from within the IDE.
  • IntelliSense technology and code completion, which allow you to enter code with fewer errors and much less typing. Syntax errors are flagged immediately, allowing you to fix problems as they are entered.
  • The tabbed document interface, which provides convenient access to multiple design and code windows.
  • All the languages use the same code editor for a shortened learning curve. Each language can have specialized features, but all benefit from features such as incremental search, code outlining, collapsing text, line numbering, and color-coded keywords.
  • The HTML editor, which provides both Design and HTML views that update each other in real time.
  • The Solution Explorer, which displays all the files comprising your solution (which is a collection of projects) in a hierarchical, visual manner.
  • The integrated Debugger, which allows you to set breakpoints and step through code, even across multiple languages.
All of these features, and more, will be covered in subsequent chapters. For now, you will use the IDE to create a simple Hello World web page.
Open Visual Studio .NET. You should see a window similar to Figure 2-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!
Chapter 3: Events
In Chapter 2, you saw 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.
In order to talk about events, you need to understand controls. In order to talk about controls, you must first know about events. We'll solve this classic chicken-and-egg problem by providing just enough information in this chapter about controls to understand events. The next two chapters will cover controls in depth.
There are two models of program execution, which are not necessarily mutually exclusive: 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
There are two models of program execution, which are not necessarily mutually exclusive: 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 (i.e., 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# 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)
and 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. The specifics of the event argument for each control are detailed in Chapter 5.
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. For a complete description of controls and data binding, see Chapter 9.
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
Both the page and controls expose 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, need to 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!
Chapter 4: Controls
Controls are the building blocks of a graphical user interface. 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 ,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. Validation controls are covered in Chapter 8.
User controls and custom controls
Controls created by the developer. User and custom controls are covered in Chapter 14.
HTML server controls and ASP controls both offer significant improvements over the old-style HTML controls. These include:
  • The ability to automatically maintain state, covered in detail in Chapter 6.
  • Browser independence. ASP.NET detects the level of the target browser. Up-level DHTML browsers are sent script for client-side processing. On downlevel standard browsers, all processing is done on the server. The appropriate HTML is generated for each browser.
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.
In order 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. If you 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" />
where 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" 
         size="40" 
         text="Enter book name."
         runat="server" />

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

      <asp:Button
         id="btnBookName" 
         text="Book Name" 
         onClick="btnBookName_Click" 
         runat="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!
Chapter 5: ASP Control Details
The previous chapter 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, ASPcontrols, 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 covers 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#, csASPServerControlBasics.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.
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#, csASPServerControlBasics.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 by the label. 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, etc.
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 (i.e., 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 (i.e., 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. Figure 5-3 shows the web page that results from running the example code.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
HyperLink Control
A HyperLink control looks similar to a LinkButton control. However, there is a fundamental difference: the HyperLink control only navigates to the target URL, while the LinkButton control posts the form and, if the event handler chooses, navigates to the target URL.
The HyperLink control has four specific attributes:
ImageURL
The path to an image (rather than text) to display. If this attribute is used, the control appears to the user as identical to an ImageButton control, although the ImageButton control still posts the form and the HyperLink control only navigates.
NavigateURL
The target URL to navigate to.
Text
The text string that will be displayed on the browser as the link. If both the Text and ImageURL properties are set, the ImageURL takes precedence. The text is displayed if the image is unavailable.
If the browser supports tool tips and the ToolTip property has not been set, then the Text value will display as a tool tip. If the ToolTip property has been set, then the ToolTip text string will display as a tool tip.
Target
Defines the target window or frame that will load the linked page. The value is case insensitive and must begin with a character in the range of a to z, except for the special values shown in Table 5-3, all of which begin with an underscore.
Table 5-3: Special values of the Target attribute
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Selecting Values
Several ASP controls allow the user to select a value or values:
CheckBox
Allows selection of Boolean data
RadioButton
Allows only a single option to be selected
CheckBoxList
Group of CheckBox controls that can be dynamically created and bound to a data source
RadioButtonList
Group of RadioButton controls that can be dynamically created and bound to a data source
ListBox
Allows selection of one or more items from a predefined list
DropDownList
Similar to a ListBox, but allows only a single selection
All of these controls derive from the WebControl class. The RadioButton derives further from the CheckBox class, and the last four controls, the List controls, all derive from the abstract ListControl class. Each of these controls is considered in detail in the upcoming sections.
A CheckBox control provides a means for a user to select Boolean data (i.e., Yes/No or True/False). If you have several checkboxes arranged together (not to be confused with a CheckBoxList), then you can select multiple options. No option is mutually exclusive of another.
The C# code in Example 5-10 shows the use of three independent CheckBoxes to control the appearance of a Label. (The equivalent VB.NET code, which is nearly identical to the C# code, is shown in Example 5-11.) Clicking on any of the checkboxes in these examples -- Underline, Overline, or Strikeout -- imposes that attribute on the text string in the Label control. The results of the C# code are shown in Figure 5-5.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!