BUY THIS BOOK
Add to Cart

Print Book $49.95


Add to Cart

Print+PDF $64.94

Add to Cart

PDF $39.99

Safari Books Online

What is this?

Add to UK Cart

Print Book £35.50

What is this?

Looking to Reprint or License this content?


Programming ASP.NET
Programming ASP.NET, Third Edition Building Web Applications and Services with ASP.NET 2.0 By Jesse Liberty, Dan Hurwitz
October 2005
Pages: 956

Cover | Table of Contents


Table of Contents

Chapter 1: ASP.NET 2.0
The White Rabbit put on his spectacles. "Where shall I begin, please, your Majesty?"
"Begin at the beginning" the King said gravely, "and go on till you come to the end, then stop."
Lewis Carroll
Alice's Adventures in Wonderland, Chapter XII
ASP.NET 2.0 is the successor to ASP.NET 1.x, which was the successor, in turn to Active Server Pages (ASP) and is now, arguably, the most popular and powerful way to write interactive Web Applications. Along with the development of ASP.NET has come the rapid evolution of Visual Studio 2005 (VS2005), once again arguably the most powerful and flexible tool for creating interactive web applications. VS2005 does not excel at laying out web pages (there are better tools for that, such as Dreamweaver) but nothing comes close for building interactive web sites, especially data-driven sites that interact with a server-side database.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
.NET Framework 2.0
The .NET Framework sits on top of the operating system, which can be any recently released version of Windows, including Windows 2000, Windows XP, or Windows Server 2003. Currently, the .NET Framework consists of:
  • Compilers for five official languages (C#, Visual Basic, Managed C++, J#, and the Jscript scripting language).
  • A number of related class libraries, collectively known as the Framework Class Library (FCL) , that include support for Windows and web applications, data access, web services, and more.
  • The Common Language Runtime (CLR), the object-oriented engine at the heart of the Framework that translates the intermediate code generated by the language compilers into the native code required to execute the application.
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.
Because the CLR translates all code to a common interactive language that is later complied to native code, .NET can, in principle, be implemented on Unix, Linux, Mac OS X, or any other operating system.
Figure 1-1 breaks down the .NET Framework into its architectural components.
Figure 1-1: .NET Framework architecture
The 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, web sites, and Windows forms. Collectively, these classes are known as the FCL. With more than 5,000 classes, the FCL facilitates rapid development of 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!
ASP.NET 2.0
ASP.NET 2.0 is the umbrella term for the combination of two web development technologies: web sites and web services. Using ASP.NET 2.0, it is easier than ever to create web sites 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.
VS2005 allows you to apply Rapid Application Development (RAD) techniques to building web applications: Drag and drop controls onto your form, double-click on a control, and write the code to respond to the associated event.
Generally, 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 2.0 has classes to facilitate the creation of standards-compliant web services and web clients, and tools incorporated into Visual Studio 2005 help enforce conformance.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
New Features
ASP.NET 2.0 includes a new Web Site Administration Tool that provides a wizard interface for web-site maintenance, as shown in Figure 1-2.
Figure 1-2: Web Site Application Administration Tool
From within this tool you can establish the database provider both for security and for role management, and you can manage your Application, SMTP, and other site management settings. The web site configuration tool is described fully in Chapter 18.
Web sites can now include an App_Code folder immediately below the application root. You may put source code into this folder and it will be compiled automatically every time the web app is run. In addition, an App_Data folder is reserved for databases, and there are additional special folders for XML files, for localization, and for skins and themes (see Chapter 13).
ASP.NET 2.0 takes advantage of the new language feature of "partial classes." In short, this allows VS2005 to separate the tool-generated code from your code, simplifying your tasks and making your code easier to read and maintain.
ASP.NET 2.0 includes a number of controls and scripts that make implementing web-based security far simpler than in previous versions of ASP.NET. The login and related controls are covered in detail in Chapter 11.
ASP.NET 2.0 includes a number of controls that allow a user to personalize the web site's user interface, using themes and skins and related controls. These are covered in detail in Chapter 13.
The site developer can easily implement a consistent look and feel across site pages using Master pages that define (relatively) invariant parts of the page. Master pages are covered in Chapter 12.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
On to VS2005
It always shocks me that developers spend so much of their time working in Visual Studio but invest so little time learning all its tricks and traps. Investing your time in learning to use VS2005 well pays off many times over, because the VS2005 is the single point of development, testing, and deployment for your entire web application. The next chapter delves into VS2005 in depth.
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 2005
Visual Studio 2005 (VS2005) is an invaluable tool for creating robust and elegant applications with few bugs in a minimum amount of time. VS2005 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.
  • What You See Is What You Get (WYSIWYG) visual design of Windows and Web Forms.
  • Code completion, which allows you to enter code with fewer errors and less typing.
  • Intellisense, which displays tips for every method, providing the return type and the types of all the parameters.
  • Dynamic, context-sensitive help, which allows you to view topics and samples relevant to the code you are writing at the moment. You also can 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 Design and HTML views that update each other in real time.
  • A Solution Explorer, which displays in outline form all the files comprising your solution.
  • An integrated Debugger, which allows you to step through code, observe program runtime behavior, and set breakpoints, even across multiple languages and multiple processes.
  • Integrated support for source control software, such as Visual Source Safe.
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 VS2005 for the first time (unless you configure it otherwise), you'll find yourself looking at the VS2005 application window, as shown in Figure 2-1.
Along the top of the application window is a typical collection of Windows menu items and buttons, plus several that are specific to the VS2005 Integrated Development Environment (IDE). Specialized tabs that provide access to tools and controls, and to other servers and databases in the development environment, appear on the left side of the application window, labeled Toolbox and Server Explorer, respectively. The
Figure 2-1: Visual Studio 2005 Start Page
Solution Explorer, for exploring the files and classes associated with a particular project, appears on the right side. More windows are available through the VS2005 menu bar (see "The Integrated Development Environment (IDE)").
At the center of the application window is the Start Page, which contains links for creating new projects and web sites or opening existing ones. It also contains several windows with links to helpful topics for getting started and up-to-date news items.
In a tradition that goes back to the early days of computing, our first program will be a web site that displays the words "Hello World." We'll jazz it up a bit by adding a button that changes the text to "Hello Visual Studio 2005."
To begin, start VS2005 and from the Start Page click on New Web Site... or from the menu choose File New Web Site....The New Web Site dialog opens, offering a number of options, as shown in Figure 2-2.
In the Templates window, chose ASP.NET Web Site.
Below the list of templates are a set of controls for setting the location and language for your web site.
The first drop-down, Location, allows you to work on web apps in three different manners, from three different locations: File System, HTTP, and FTP. The choice
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 web application consists of many items: content files (such as .aspx files), source files (such as .cs files), assemblies (such as .exe and .dllfiles) and assembly information files, data sources (such as .mdb files), references, and icons, as well as miscellaneous other files and folders. VS2005 organizes these items into a folder that represents the web site. All the files that make up the web site are contained in a solution. When you create a new web site, VS2005 automatically creates the solution and displays it in the Solution Explorer. Additional projects (described below) can also be added to the web site.
In addition to web sites, VS2005 can create projects. These projects can be added to the solution or placed in their own solution. Many types of projects can be built in VS2005, including among others:
  • Windows Application
  • Windows Service
  • Windows Control Libray
  • Web Control Library
  • Class Library
  • Pocket PC Application, Class Library, Control Library, or Empty Project
  • SmartPhone Application, Class Library, or Empty Project
  • Windows CE Application, Class Library, Control Library, or Empty Project
  • SQL Server Project
  • Empty Project
Notable in its absence from the above list are Web Applications. Web applications are not contained within projects, just solutions and, as you saw above, you open new web sites directly, using File New Web Site... rather than File New Project. You can, however, add a project to a web application solution. You will see this demonstrated in Chapter 19 when you learn how to create setup projects for deploying your finished web site.
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 VS2005 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.
But more important than the physical layout of the IDE is the productivity boost it provides to you, the developer. You can visually drag controls from the toolbox onto a design window or a code window. In code editing windows , Intellisense automatically pops up a list of all the available members for any given situation. Syntax errors are highighted in code windows, signalling a problem even before you try to compile the project. The list goes on: a little time invested getting familiar with the IDE will reap tremendous payback.
VS2005 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-7. Basically, it consists of a menu and toolbar arrangement across the top and a work surface below, flanked by other toolbars and windows.
Figure 2-7: Typical IDE layout
When working on content files, such as page, user control, or master page files, which all have visual content, you have your choice of two different views, selectable by tabs at the bottom of the screen. Design view shows the content in a WYSIWYG mode. Source view shows the source code for the content, that is, the server control declarations, any HTML and static content, and any script blocks on the page.
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: Controls: Fundamental Concepts
Controls are the building blocks of a graphical user interface (GUI). Some controls you're probably familiar with include buttons, checkboxes, and list boxes. Controls provide a means for a user to indicate a preference, enter data, or make selections. They can also provide infrastructure support in areas such as validation, data manipulation, master pages, and security .
There are four types of web controls (each but the first will be covered in detail in this and subsequent chapters):
HTML controls
The original controls available to any HTML page. These all work in ASP.NET 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 and XHTML: The Definitive Guide, Fifth Edition, by Chuck Musciano and Bill Kennedy (O'Reilly).
HTML server controls
These are based on the original HTML controls but are enhanced to enable server-side processing.
ASP.NET server controls
These rich and flexible server-side controls are integrated into the ASP.NET programming model. These controls are rendered to the client as HTML and provide the same functionality as HTML server controls and more.
User controls and custom controls
Controls created by the developer. Chapter 14 discusses user and custom controls.
ASP.NET server controls (sometimes called ASP controls because of the way they are coded in content files) are at the heart of ASP.NET, replacing classic client-side HTML controls with a server-side implementation that integrates with and follows the object-oriented programming model of the .NET Framework. Most important, ASP.NET server controls remove all the inconsistencies of how attributes are set in HTML controls: ASP.NET server controls are predictable.
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
The two models of program execution (which are not necessarily mutually exclusive) are linear and event-driven. The key to understanding ASP.NET is that it is event-driven.
Linear programs move 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 method calls) may redirect the flow of the program, but essentially, once the program execution begins, it runs its course unaffected by anything the user or system may do. Before GUI environments, most computer programs were linear.
In contrast, event-driven programming responds to something happening (such as a button being pressed). Most often, events are generated by user action, but events can be raised by the system. 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.
In ASP.NET, objects may raise events and other objects may have assigned event handlers. For example, a button may raise the Click event, and the page may have a method to handle the button's click event (such as Button1_Click). Your code in the event handler then responds to the button's being clicked in whatever way is appropriate for your application.
The main point to remember here is that server controls are objects that can raise events. Any action a user takes with a server control on the browser raises an event. Your server-side code responds to that event, running the code you have placed in the event handler method.
ASP.NET has thousands of events. The application has events (such as Start and End), each session has events (again, such as Start and End), and the page and most of the server controls can raise events. All ASP.NET events are handled on the server. Some events cause an immediate posting to the server, and other events are stored until the next time the page is posted back to 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!
ASP.NET Server Controls
The primary control type used in ASP.NET is the ASP.NET server control. Server controls may have methods and event handlers associated with them, and this code is processed on the server. (Some server controls provide client-side script as well, but even then the processing is done, again, on the server.)
If the control has a visual component (e.g., labels, buttons, and tables), ASP.NET renders classic HTML to the browser, taking the target browser capabilities into account. If the ASP.NET server control requires client-side script to implement its functionality as, for example, with the validation controls described in Chapter 8, then browser-appropriate script is generated and sent to the browser. However, server-side validation will be performed as well.
This is a key point and bears repeating: What is sent to the client is plain vanilla HTML, so ASP.NET programs can be run on any browser by any manufacturer. All processing is done on the server, and all ASP.NET server controls are presented to the browser as standard HTML. Sending script is an optimization and is never required.
ASP.NET server controls offer a consistent programming model. 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.NET server 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.NET server controls in general, all the declared attributes correspond to properties of the class that represents the control.
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
This book focuses on using ASP.NET server controls . However, understanding and using HTML and HTML server controls can be useful in real-life applications.
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.
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 the control contents 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 two main reasons for using HTML server controls rather than ASP.NET server controls:
Converting existing HTML pages to run under ASP.NET
To convert an HTML file to run under ASP.NET, all you need to do is change the extension of the file to .aspx. However, the HTML controls will run client side, not server side. To take advantage of server-side processing, including automatic maintenance of state (see Chapter 6), you must add the runat attribute.
Using HTML tables for page layout
Server-side controls consume server resources. For static tables commonly used to lay out the page, server-side processing is unnecessary unless you need to refer to one or more of the table elements in your code. The following example illustrates this point.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Client-Side Processing
Server-side processing is at the heart of ASP.NET. However, this approach does have some shortcomings. The main problem is that a postback to the server is required before any processing can occur. Even for intranet applications connected to the server with a high-speed local network connection, this introduces a noticeable delay often unacceptable to the user experience. For Internet applications, even those connected via high-speed broadband, the delays can seem interminable.
Client-side processing can greatly enhance the user experience, providing nearly instantaneous response to user actions. This is accomplished using scripting languages such as JavaScript or VBScript.
Some ASP.NET server controls use client-side scripting to provide responses to user actions without posting back to the server. For example, validation controls typically download script to the browser so invalid data are caught and flagged to the user without requiring a round trip to the server. However, in these cases, this client-side script is provided by ASP.NET and you, the developer, do not have to write or manage that script.
As you will see, calling client-side code from any ASP.NET server control is possible. In addition, the ASP.NET Button server control has a property, OnClientClick, that lets you specify client-side script to execute when the button is clicked.
Conventional and server HTML controls expose a number of events that can execute script when they are raised. This script can be contained in a script block in the content file or contained in-line with the attributes in the control declaration. Previously, you saw the onclick and onserverclick attributes for the HTML Button control for handling click events. Table 3-6 lists a few of the commonly used events available to HTML controls.
Table 3-6: Commonly used HTML events
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: Basic Controls
Chapter 3 introduced controls. Though it briefly mentioned both server and classic HTML controls, most of the coverage was on ASP.NET server controls, the heart of ASP.NET.
As noted previously, server controls are known variously as "ASP controls," "ASP.NET controls," "ASP.NET server controls," "Web controls," and "Web server controls." In this book, we will use "ASP.NET server control" or "server control." When referring to "server control," it should be clear from the context if this means only ASP.NET server controls or includes HTML server controls as well.
Topics common to all ASP.NET server controls were covered, such as events, syntax, programmatic access to controls during runtime (using the ID property), and the use of VS2005 to build your web site using controls. However, it did not go into significant detail about any specific controls.
This chapter provides a wealth of detail about many of the basic ASP.NET controls, including the TextBox, Button, CheckBox, and RadioButton controls, lists, tables, and images. It discusses the features and properties common to many controls and surveys the specific details of the basic ASP.NET server controls included with the .NET Framework.
The next chapter will cover many of the advanced server controls included as part of ASP.NET, such as view controls, and the Wizard, FileUpload, AdRotator, and Calendar controls. Other chapters will focus on data controls, validation controls, login and security controls, and so on.
In this section, you will create a simple web page two different ways: once using a generic text editor (Notepad) and then again using VS2005. The purpose of this exercise is to show you how to create a web site using any text editor and to show you how much easier it is to use VS2005.
This is the only time in the entire book you will create a web site without using VS2005.
Using either technique, the resulting web page should look something like that shown in Figure 4-1. This page will demonstrate some of the properties, events, and methods common to all ASP.NET server controls.
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 two different ways: once using a generic text editor (Notepad) and then again using VS2005. The purpose of this exercise is to show you how to create a web site using any text editor and to show you how much easier it is to use VS2005.
This is the only time in the entire book you will create a web site without using VS2005.
Using either technique, the resulting web page should look something like that shown in Figure 4-1. This page will demonstrate some of the properties, events, and methods common to all ASP.NET server controls.
Figure 4-1: ASP.NET server controls: Basics
To create this web page without benefit of VS2005, open Notepad or your favorite editor capable of creating a flat text file (not Microsoft Word, for example, unless you want to jump through hoops). Enter the code in Example 4-1 into the file.
Example 4-1. ASPNETServerControlBasics-TextEditor.aspx
<%@ Page Language="C#" %>
<script runat="server">
   void lblTime_Init(object sender, 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 id="form1" runat="server">
         <h2>Basics</h2>
         <asp:Label ID="lblTime" runat="server"
                    OnInit="lblTime_Init" />
      </form>
   </body>
</html>
Save the file as ASPNETServerControlBasics-TextEditor.aspx in any folder you want, say c:\websites.
To easily see your page processed by ASP.NET on a web server, you need to access the page in a browser via localhost . You must create a virtual directory for the folder that contains the web page file.
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
You use a Label control to display text. The Label control's Text property contains the text string to be displayed. Text is the only Label control property that is not inherited from the Control or WebControl classes. The Label control has no events or methods that are not derived from Control or WebControl.
You have seen the Label control used in code examples in previous chapters. You can set the Text and Font properties of the Label control programmatically (as shown in Examples 4-1 and 4-3) or declaratively.
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. You can configure it to be single line or multiline or to accept passwords. If you set it to 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. The TextBox, DropDownList, Label, and other text-friendly controls implement the ITextControl interface, which is new to Version 2.0 of ASP.NET. This interface has a single property, Text, which is the visual content of the control.
Table 4-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 4-2: Some properties specific to the TextBox control
Name
Type
Get
Set
Values
Description
AutoPostBack
Boolean
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
HiddenField Control
Hidden fields were a common trick of the HTML web developer's trade for carrying information within a page when you did not want that information to be visible to the user.
An easier and more elegant way of accomplishing this task is to use one of the state mechanisms provided by the .NET Framework (see Chapter 6 for a complete discussion of state). However, sometimes this is impossible, perhaps for performance, bandwidth , or security reasons. (Performance and bandwidth are really two sides of the same coin.)
In classic HTML pages, you might use something such as the following code snippet to implement a hidden field:
<input type="hidden" value="foo">
ASP.NET uses a hidden field to implement view state. You can see this by examining the source that is rendered to the browser, via the View Source menu command in Internet Explorer. (Other browsers have analogous commands.) You will see something similar to the following, where the value attribute encodes all the information saved in view state.
<input type="hidden" name="_  _VIEWSTATE"
   value="/wEPDwUJL0CHlBR...YfL+BDX7xhMw=" />
To reap the benefits of server-side processing, you can convert this into an HTML server control with the addition of id and runat attributes:
<input type="hidden" value="foo" id="myHiddenControl" runat="server">
An ASP.NET HiddenField control is best of all these options (assuming there is some compelling reason not to use ASP.NET's state capabilities) because it adds the following features:
  • Programming consistency
  • Easy access to the Value property, which holds the value being maintained by the control
  • The ClientID property, inherited from Control, which provides the ID attribute of the control itself
  • Access to the ValueChanged
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 ASP.NET Button controls, all members of the System.Web.UI.WebControls namespace:
Button
This is the standard button.
LinkButton
The LinkButton control is sort of a cross between a standard button and a HyperLink control (described in the next section). A LinkButton appears to the user as a hyperlink (i.e., the text is colored and underlined).
Figure 4-3: HiddenFieldDemo
ImageButton
The ImageButton control performs the same function as the standard button, except that an image bitmap takes the place of the button on the browser UI. For the ImageButton control, there is no Text attribute but there is an AlternateText attribute, which specifies what text to display on non-graphical browsers.
In addition, the event handler uses an ImageClickEventArgs event argument, which is different than the event handlers for the Button and LinkButton controls. This event argument exposes two fields (not used in this example) containing the X and Y coordinates of the location where the user clicked on the image. These fields could be used to implement your own image map type of functionality.
In addition to all the properties, methods, and events inherited 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!
HyperLink Control
A HyperLink control looks similar to a LinkButton control with a fundamental difference: the HyperLink control immediately navigates to the target URL without a postback, while the LinkButton control posts the form. If the LinkButton event handler chooses, it will navigate to the target URL. A HyperLink control behaves very similarly to an HTML control.
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, though 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 the Text and ImageUrl properties are both set, the ImageUrl takes precedence. The text will be displayed if the image is unavailable.
If the browser supports tool tips and the ToolTip property (inherited from the WebControl class) has not been set, the Text value will display as a tool tip. If the ToolTip property has been set, 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 4-3, all of which begin with an underscore.
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.NET server controls allow the user to select a value or values:
CheckBox
Allows selection of Boolean data
CheckBoxList
Group of CheckBox controls that can be dynamically created and bound to a data source
RadioButton
Allows only a single option to be selected from a group
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
BulletedList
Formatted with bullets and can be simple text or a link
All of these controls derive from the WebControl class. The RadioButton derives further from the CheckBox class, and the list controls all derive from the abstract ListControl class. Each of these controls is considered in detail in 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
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 from a List
ASP.NET provides five server controls for selecting single or multiple items from a list:
  • BulletedList
  • CheckBoxList
  • DropDownList
  • ListBox
  • RadioButtonList
All of these controls are derived from ListControl and have much in common:
  • ListItem (the information displayed by the list) works exactly the same way for all the ListControls, with a Value property and a Text property.
  • The Items property of the control contains the collection of all the ListItems.
  • ListItems can be added to the Items collection either statically, i.e., declaratively in the content file, programmatically through the Add method, or from a data source.
    The Data Source Configuration Wizard or the ListItem Collection Editor can be easily accessed by clicking the control's smart tag, the little icon in the upper-right corner of the control.
  • The SelectedIndex and SelectedItem properties of the control point to the selected item with the lowest index. For single select controls, such as the DropDownList, the RadioButtonList, and the ListBox (if the SelectionMode property is set to ListSelectionMode.Single, the default value), the selected index is by definition, the lowest index. For multi-select controls, such as
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Tables
Tables are very important in web page design as they are one of the primary means of controlling the layout on the page. In pure HTML, several tags create and format tables, and many of those have analogs in ASP.NET server controls. If you don't need server-side capabilities, then you will be fine using the static HTML tags. But when you need to control the table at runtime, then server controls are the way to go. (You could also use HTML server controls, described in the previous chapter, but they don't offer the consistency of implementation and object model offered by ASP.NET controls.)
Table 4-10 summarizes the ASP.NET server controls used to create tables in web pages.
Table 4-10: ASP.NET server controls used to create tables in web pages
ASP.NET server control
HTML Analog
Description
Table
<table>
Parent control for TableRow controls. The Rows property of the Table object is a collection of TableRow objects.
TableRow
Additional content appearing in this section has been removed.