JavaScript EditorJavascript debugger     Javascript examples


Team LiB
Previous Section Next Section

Types of Controls

As discussed briefly in Chapter 7, the built-in server controls in ASP.NET are divided into two groups, HTML controls and Web controls, each of which is contained in its own namespace. In this section, I’ll discuss the available controls in each group and show examples of when and how to use each type of control. I’ll also discuss some of the specialized Web controls, including the Calendar and AdRotator controls, as well as the Validation server controls.

HTML Controls

The HTML controls map 1-to-1 with the standard HTML elements. However, some HTML elements don’t map directly to a specific HTML control. Why would you want to use an HTML control instead of just coding HTML? Because you can easily manipulate the look and functionality of the page at runtime by changing the control’s attributes programmatically.

The HTML controls reside in the System.Web.UI.HtmlControls namespace, which is available to Web Forms pages automatically. Table 8-1 describes how HTML elements map to HTML controls.

Table 8-1: Mapping of HTML Elements to HTML Controls

HTML Element

Control Type

Purpose

<a> Defines a hypertext link.

HtmlAnchor

Provides programmatic access to an HTML anchor element. Exposes a ServerClick event.

<button> Renders an HTML button.

HtmlButton

Provides programmatic access to an HTML button element. This element is defined in the HTML 4.0 spec and is supported only by Microsoft Internet Explorer 4.0 and higher. Exposes a ServerClick event.

<form> Denotes an HTML form container.

HtmlForm

Provides programmatic access to an HTML form element. Acts as a container for other server controls. Any controls that need to participate in postbacks should be contained within an HtmlForm control.

<img> Embeds an image or video clip.

HtmlImage

Provides programmatic access to an HTML image element.

<input type=“button”> <input type=“submit”> <input type=“reset”> Specifies a form input control.

HtmlInputButton

Provides programmatic access to an HTML input element for the button, submit, and reset input types. Exposes a ServerClick event.

<input type=“checkbox”> Specifies a form input control.

HtmlInputCheckBox

Provides programmatic access to an HTML input element for the checkbox input type. Exposes a ServerChange event.

<input type=“file”> Specifies a form input control.

HtmlInputFile

Provides programmatic access to an HTML input element for the file input type.

<input type=“hidden”> Specifies a form input control.

HtmlInputHidden

Provides programmatic access to an HTML input element for the hidden input type. Exposes a ServerChange event.

<input type=“image”> Specifies a form input control.

HtmlInputImage

Provides programmatic access to an HTML input element for the image input type. Exposes a ServerClick event.

<input type=“radio”> Specifies a form input type.

HtmlInputRadioButton

Provides programmatic access to an HTML input element input control for the radio input type. Exposes a ServerChange event.

<input type=“text”> <input type= “password”> Specifies a form input control.

HtmlInputText

Provides programmatic access to an HTML input element for the text and password input types. Exposes a ServerChange event.

<select> Defines a list box or drop down list.

HtmlSelect

Provides programmatic access to an HTML select element. Exposes a ServerChange event.

<table> Denotes a section of tags organized into rows and columns.

HtmlTable

Provides programmatic access to an HTML table element. Note that some table subelements (such as <col>, <tbody>, <thead>, and <tfoot>) are not supported by the HtmlTable control.

<td> and <th> Denote table cells and header rows.

HtmlTableCell

Provides programmatic access to HTML table cell elements.

<tr> Denotes a table row.

HtmlTableRow

Provides programmatic access to HTML table row elements.

<textarea> Specifies a multi-line text input control.

HtmlTextArea

Provides programmatic access to an HTML text area element. Exposes a ServerChange event.

<body>, <div>, <span>, <font>, etc.

HtmlGenericControl

Provides programmatic access to any HTML element not specifically represented by its own HTML control class.

Each HTML control class is derived from the generic HtmlControl class. This class provides methods and properties common to all HTML controls, such as the Attributes collection, which provides a collection of name/value pairs for any attributes contained in the tag definition for the control (such as id=“myControl” or border=“1”). The individual control classes then expose additional methods and properties that are specific to the HTML element that they represent. For example, the HtmlAnchor control exposes an Href property that allows you to programmatically modify the URL to which the anchor tag is linked, as well as a Target property, which allows you to modify the target of the anchor tag.

Note 

Because the HTML controls do not expose a strongly typed control equivalent for every HTML element, you can use the Attributes collection to programmatically add tag attributes to any HTML control. This allows you to programmatically set tag attributes that are not exposed as properties by the HTML control classes:

HtmlInputText myTB = new HtmlInputText();
myTB.Attributes("onBlur") = "javascript:alert('Lost focus!');";

Many of the HTML controls also expose events to which you can respond (above and beyond the standard events inherited from HtmlControl). Some HTML controls expose a ServerClick event and some expose a ServerChange event. The table starting on page 230 lists which controls support which event.

Note 

Unlike the server controls in the Web control namespace, which handle only server-side events, HTML controls can handle both server-side events and any client-side events that exist for the HTML element to which they map. For example, the HtmlInputButton control supports both the server-side ServerClick event and the client-side Click event.

To handle both events, you’d use the following tag declaration:

<input type="submit" onclick="client_handler"
   onserverclick="server_handler" runat="server"/>

This allows you to perform actions on the client before the page is posted back to the server, if desired.

Because of their close mapping to individual HTML elements, HTML controls provide the fastest and easiest path for moving from static HTML to the power of ASP.NET server controls.

In Web Forms pages, there are three basic rules of the game when it comes to case sensitivity.

  • Namespaces and class names are case sensitive. For example, namespaces imported using the @ Import directive will cause an error if the correct case is not used. This is a common cause of errors for those just getting started with ASP.NET.

  • Tag names and attributes are not case sensitive. This also applies to server control properties expressed as tag attributes.

  • Control names used in <script> blocks or in code-behind classes might or might not be case sensitive, depending on whether the language you’re using is case sensitive. C# is case sensitive, for example, so using the incorrect case for a control name or property in C# code can lead to errors. Though Visual Basic .NET is not case-sensitive, you should still use case consistently, to ensure that your code is easy to read and maintain.

    Note 

    When you’re working with a case-sensitive language, or when you receive errors such as “The Namespace or type <namespace> for the Import ‘System.<namespace>’ cannot be found,” it’s usually a good idea to check for incorrect case in control, class, or namespace names.

HTML Control Examples

To demonstrate the simplicity and power of HTML controls, let’s take a look at some examples. Let’s say you have the following static HTML page:

<html> <body> <p>This is some simple HTML text.</p> </body> </html>

By simply adding the runat=“server” attribute and an id attribute to the <body> and <p> elements, you can turn these elements into HtmlGenericControls:

<html> <body id="Body" runat="server"> <p id="TextPara" runat="server">This is some simple HTML text.</p> </body> </html>

Once you’ve converted the elements to HTML controls, it is fairly simple to manipulate them in server-side code:

<html> <head> <script language="cs" runat="server"> void Page_Load(Object sender, EventArgs e  Body.Attributes["bgcolor"] = "Gray" TextPara.Attributes["style"] = "color:Red;font-size:large;"  </script> </head> <body id="Body" runat="server"> <p id="TextPara" runat="server">This is some simple HTML text.</p> </body> </html>

If you save this code in a file with the .aspx extension to a directory set up as a virtual directory in IIS and browse the page, the output should look like the illustration on the next page.

Click To expand

HTML controls are useful for dynamically adding and removing HTML table rows or <select> items. In the following example, you’ll see how to dynamically add and remove items in a drop-down list created by an HtmlSelect control.

Add and remove list items dynamically

  1. Create a new project in Visual Studio .NET. Name the project Chapter_08. (To avoid conflicting with the practice files—if they’re installed—do not create this project under http://localhost/aspnetsbs.)

  2. Add a new Web Form to the project and type its name as HtmlSelect.aspx.

  3. Switch to HTML view and add the following HTML markup to the page between the <form> and </form> tags:

    What's your favorite ice cream?<br/> <select id="IceCream" size="1">    <option>Chocolate</option>    <option>Strawberry</option>    <option>Vanilla</option> </select> <input id="Enter" type="button" value="Enter"> <h3><span id="Fave"></span></h3>
  4. Switch back to design view. The page should look similar to the illustration on the following page.

    Click To expand
  5. Right-click the drop-down list representing the <select> element, and select Run As Server Control. Repeat for the button element. Note the glyphs that Visual Studio .NET adds to these elements, indicating that they are now server controls. The glyphs are shown in the following illustration.

    Click To expand

    Because the <span> element has no representation in design view, you’ll need to add the runat=“server” attribute to this element manually.

  6. Switch to HTML view, and then add the runat=“server” attribute to the <span> element to transform it into a server control.

  7. Switch back to design view and double-click in an open area of the page. This will open the code-behind module for the page, and place the cursor in the Page_Load event handler. Add the following code— which adds two items to the HtmlSelect control and removes one from it—to the Page_Load event handler:

    if (!IsPostBack  IceCream.Items.Add("Pistachio") IceCream.Items.Add("Rocky Road") // We don't like Strawberr IceCream.Items.Remove("Strawberry") }
  8. Using the tabs at the top of the editor window, switch back to HtmlSelect.aspx. Double-click the button. This will add the Enter_ServerClick event handler to the code-behind module, and switch you back to the code-behind module. Add the following code to the Enter_ServerClick event handler:

    Fave.InnerHtml = "Your favorite is " + IceCream.Value + "!";
  9. Save the page and code-behind module, build the project, and then browse the page. The output should look similar to the following illustration.

    Click To expand
  10. Select Rocky Road from the drop-down list, and then press the Enter button. The output should look similar to the illustration on the following page.

    Click To expand

Web Controls

Web controls are truly the gem in the crown of ASP.NET. These server controls give you an unprecedented level of productivity by providing a rich, event- driven programming model, similar to that of Microsoft Visual Basic. The Web controls reside in the System.Web.UI.WebControls namespace, which is available to all Web Forms pages automatically.

The Web controls run the gamut of functionality, from simple controls such as the Button, TextBox, and Label controls, to the richer ListBox and DropDownList controls, to the even richer Calendar and AdRotator controls. There are even controls especially designed for data binding, including the DataGrid, DataList, and Repeater controls. You’ll see examples of these controls in later sections.

Note 

Although the System.Web.UI.WebControls and System.Web.UI.HtmlControls namespaces are available to Web Forms pages automatically, the same is not true of code-behind pages associated with Web Forms pages. If you want to use controls in either of these namespaces without using the fully qualified class name, you need to add the appropriate Using statement to your code- behind class to import the namespace.

Adding Server Controls to a Page

As you saw in Chapter 7, adding server controls to a page is fairly easy. There are two different ways to add controls to a page, declaratively and programmatically. Either way allows you to set properties of the control as desired, and either one can be used to place a control where you want it on the page.

Adding Controls Declaratively

As you saw earlier in this chapter, the ASP.NET HTML controls use essentially the same syntax as standard HTML elements, with the exception of the runat attribute, which is always set to server. Web controls also use a tag-based syntax, but are prefaced with asp:. So, you’d declare an HtmlInputButton server control with the following syntax:

<input id="Enter" type="button" value="Enter"     OnServerClick="Enter_Click" runat="server">

You would declare an ASP.NET Button server control with the following syntax:

<asp:button id="Enter" Text="Enter" OnClick="Enter_Click    runat="server" />

Notice that in the second example, a forward slash character (/) is added before the closing angle bracket (>). This is required when you do not use a complete closing tag. Here’s an example of when you’d use a closing tag:

<asp:label id="myLabel" runat="server">Hi there!</asp:label>

You enclose the literal text Hi there! between opening and closing tags. The literal text becomes the Text property of the Label control. The Label control, which renders as a <span> on the client side, is one of a number of controls that allow you to enclose literal text for the Text property (or some other property of the control) between the opening and closing tags. Other controls include the Literal, Panel, PlaceHolder, and TextBox controls.

You could also accomplish the same result by using a single-tag syntax:

<asp:label id="myLabel" text="Hi there! " runat="server"/>

When you add a control to the page declaratively, you are doing two things: giving the control enough information to be created and initialized properly, and setting the properties for the control. The first part is accomplished by the asp: prefix and the tag name, plus the id and runat attributes. Only the prefix/ tag name and the runat attribute are required to create a server control, but the id attribute is required if you want to refer to the control in server-side code.

Once you’ve provided this minimum information, you can set additional properties by adding attributes to the tag declaration corresponding to the property you want to set. For example, if you wanted to set the Visible property of a Label control to false (to set up a message declaratively and show it by making it visible later in server-side code), you would modify the declaration as follows:

<asp:label id="myLabel" text="Hi there! " visible="false"     runat="server"/>

Some of the more feature-filled controls, such as the DataGrid control, use a combination of attributes in the main tag definition and subtags that declare additional controls or set properties (such as the ItemStyle and AlternatingItemStyle tags that can be used with the DataGrid or DataList controls) to define the properties for the control. You’ll see examples of these controls later in this chapter.

Adding and Manipulating Controls Programmatically

Although adding controls to the page declaratively is probably the most straightforward approach, you can also add controls to the page and manipulate them programmatically. This gives you greater control because you can choose how and whether to add controls at run time.

Adding a control programmatically is as simple as declaring a new instance of the control class and adding it to the page’s Controls collection, as follows:

Label myLabel = new Label() // You can also just use Controls, but the Page reference makes it  // clear what you intend, which is always a good idea Page.Controls.Add(myLabel) myLabel.Text = "Hi there! ";

The preceding code creates the Label control and sets its text property to Hi there!. There’s just one problem. As written, the code adds the control to the end of the page’s Controls collection, which is actually after the closing <body> and <html> tags, which ASP.NET treats as Literal controls on the server. The code that is sent to the browser is shown here:

<html> <head> </head> <body> </body> </html> <span>Hi there!</span>

While this output will still be rendered in most browsers, the incorrect HTML syntax makes it less than ideal. This presents even more of a problem when you are dealing with both declarative and programmatically created controls. Creating controls out of order can produce unintended results. So what do you do?

One option is to call the AddAt method of the Controls collection, instead of Add. AddAt takes two arguments: an integer representing the location in the collection where the control should be added, and the name of the control to add.

Page.Controls.AddAt(3, myLabel);

The only problem is that in order to render the control where you want it in the page, you have to know exactly where the control should appear in the collection. This is not always practical.

An easier way to ensure that programmatically created controls appear where you want them to is to use a PlaceHolder control to locate the control in the page. The PlaceHolder control has no UI of its own. All of the content within a PlaceHolder control is rendered based on the controls in its Controls collection. So, to make sure that the control in the previous example is displayed within the body of the HTML document sent to the browser, you can use the following code:

<%@ Page Language="cs" %> <html> <head> <script runat="server">    void Page_Load(        Label myLabel = new Label()       myPH.Controls.Add(myLabel)       myLabel.Text = "Hi there!"     </script> </head> <body>    <asp:placeholder id="myPH" runat="server" /> </body> </html>

This produces the following HTML output:

<html> <head> </head> <body>    <span>Hi there!</span> </body> </html>

You can add multiple controls to the same placeholder, and you can use multiple placeholders in the same page.

Adding Controls with Visual Studio .NET

Of course, the easiest way to add ASP.NET server controls to a Web Forms page (and to discover all of the properties available for a control) is to use the Visual Studio .NET Toolbox. The Web Forms tab of the Toolbox is shown in the following illustration.

Click To expand

Add server controls using Visual Studio .NET

  1. Open Visual Studio .NET and then open the Chapter_08 project created earlier in this chapter.

  2. Add a new Web Form to the project. Type the name of the file as DropDownList.aspx.

  3. Open the Toolbox window by moving the mouse pointer over the Toolbox tab in the IDE. If necessary, select the Web Forms tab of the Toolbox by clicking it.

    To add a control to the page, you can simply double-click the desired server control. The control will be inserted into the page at the location of the cursor if the page is in FlowLayout mode, or at the top-left corner of the page if the page is in GridLayout mode. In GridLayout mode, you can also select a control from the Toolbox and draw it on the form as you would a Visual Basic–style control. In either FlowLayout or GridLayout mode, you can also drag and drop controls from the Toolbox onto the page at the desired location.

  4. Using one of the techniques described in the previous step, add a Label control, a DropDownList control, a Button control, and another Label control to the page. Once the controls have been added, the page should look similar to the following illustration.

    Click To expand
  5. Set the properties of the added controls as follows, using the Properties window:

    Control

    Property

    Value

    Label1

    Text

    What’s your favorite ice cream?

    Button1

    Text

    Enter

    Label2

    Text

    (blank)

    Label2

    Font-Bold

    True

    Label2

    Font-Size

    Larger

  6. Select DropDownList1 by clicking it in the designer window, and then select its Items property in the Properties window. Click the ellipsis button (…) to open the ListItem Collection Editor and edit the Items property.

  7. Use the Add button to add three items to the collection. Set their Text and Value properties by typing Chocolate, Strawberry, and Vanilla, respectively. The result should look similar to the illustration on the following page. When you are done adding items, click OK.

    Click To expand
  8. Double-click in an open area of the page. This will open the code- behind module for the page, and place the cursor in the Page_Load event handler. Add the following code, which adds two items to the DropDownList control and removes one, to the Page_Load event handler. (This code is almost identical to the code used in the HTML controls example; only the control name has been changed.)

    if (!IsPostBack  DropDownList1.Items.Add("Pistachio") DropDownList1.Items.Add("Rocky Road") // We don't like Strawberr DropDownList1.Items.Remove("Strawberry") }
  9. Using the tabs at the top of the editor window, switch back to DropDownList.aspx. Double-click the button. This will add the Button1_Click event handler to the code-behind module, and switch you back to the code-behind module. Add the following code to theButton1_Click event handler:

    Label2.Text = "Your favorite is " +  DropDownList1.SelectedItem.Value + "!";
  10. Save the page and code-behind module, build the project, and then browse the page. The output should look similar to the illustration on the next page.

    Click To expand
  11. Select Rocky Road from the drop-down list, and then click the Enter button. The output should look similar to the following illustration.

    Click To expand

Applying Styles to Controls

Once you’ve added your controls to the page, eventually you’ll probably want to make changes to how those controls are displayed. For example, you might want to make the text of a Label control red. Simply set the ForeColor property of the control to Red, as follows:

<asp:label id="myLabel" forecolor="red" runat="server">    Hi there </asp:label>

What if you want to do something more complicated? While controls such as the Label control expose properties like ForeColor and BackColor, at times these properties will not be sufficient. Let’s say you want to apply a cascading style sheet (CSS) class defined elsewhere (either in a Style block at the top of the page or in a linked style sheet) to a server control. Or maybe you just want to use CSS styles directly in your control tag.

For these occasions, the CssClass and Style properties defined in the WebControl base class (and inherited by all WebControl classes) come in handy. With the CssClass property, you can set up a CSS class such as the following:

<style type="text/css">  .mylabel { font-size:24pt; font-weight:bold; color:red;}  </style>

You can use this to format your control as follows:

<asp:label id="myLabel" cssclass="mylabel" runat="server">    Hi there </asp:label>

This technique works fine for linked style sheets as well.

You can use the Style property to specify CSS styles directly, as follows:

<asp:label id="myLabel"     style="font-size:24pt; font-weight:bold; color:red;    runat="server">    Hi there </asp:label>

Note that whether you set the color of a Label control with the ForeColor property or use the CssClass or Style properties declaratively, the result is rendered as a class or style attribute on the resulting <span> tag, which is the client-side representation of the WebControl control.

Note 

Although you can set most control properties declaratively by using the property name as an attribute of the tag used to declare the control, some compound properties (properties that are represented by another class) require that you use a slightly different attribute syntax.

A good example of this is the Font property (defined in the WebControl base class), which returns an instance of the FontInfo class. To modify the font of a control that inherits from WebControl (such as the Label control), you use attributes in the form font-<propertyname>, as follows:

<asp:label id="myLabel" font-name="arial"
   runat="server">

You can also access these properties programmatically, using the form <controlname>.Font.<propertyname>, as follows:

myLabel.Font.Name = "Arial";

Finally, you can also apply styles to your controls based on the client-side representation of the control. As noted, Label controls are rendered on the client as <span> tags, so if you define a style that applies to all <span> elements, your Label controls will also use this style. As long as you know the client-side representation of a particular control (which you can get by viewing the source of the page from the browser), you can create a style sheet to format that control.

Additional Web Control Examples

Web controls are quite easy to use and provide a great deal of flexibility. So far, you’ve used only simple examples. This section will look at a few more complex examples to demonstrate the use of various Web controls. The first example will show you how to use server controls to set up a form for sending e-mail from an ASP.NET Web Form via the Simple Mail Transport Protocol (SMTP). The second example will show you how to use Panel controls to simulate a wizard-style multipage interface within a single Web Forms page.

Sending Mail

A common task for many Web applications is sending e-mail to customers or visitors. Often, this e-mail is generated automatically, without the need for specific data entry. But site operators might also want a way to send a quick e-mail through the site. Web controls, in combination with the .NET SmtpMail and MailMessage classes, can make adding this functionality to a Web application quick and easy.

Note 

This example assumes that you have access to an SMTP server from which to send your e-mail. Microsoft Windows 2000, Microsoft Windows XP Professional, and Microsoft Windows Server 2003 come with an SMTP service that is part of the services provided by IIS. The SMTP service is relatively easy to install and configure. You can find details for setting up the SMTP service at http://msdn.microsoft.com/library/en-us/dnduwon/html/d5smtp.asp.

Add e-mail sending functionality to a Web application

  1. Open the Chapter_08 project created earlier in this chapter (if it is not already open) and add a new Web Form to the project. Type the name of the Web Form as SmtpEmail.aspx.

  2. Use the Visual Studio .NET Table editor to add an HTML table to the page (click the Table menu, then select Insert, and then select Table) to ensure that your controls line up nicely on the page. The table should have 6 rows and 2 columns, as shown in the illustration on the following page. Click OK to insert the table.

    Click To expand
  3. Add a Label control and a TextBox control to each of the first five rows of the table, as shown in the following illustration. Note that in addition to dragging controls from the toolbox to the page, you can create new controls by clicking an existing control of the desired type (such as a Label control) and dragging it to the new location while holding down the Ctrl key. (Click first, then press control and drag.) This technique has the advantage of creating a copy of the existing controls including its properties (with the exception of the ID property).

    Click To expand
  4. Add a Button control and an HtmlInputButton control with the type set to reset to the last row of the table. To add the HTML Reset button, you will need to switch to the HTML tab of the toolbox, drag the Reset Button to the appropriate table cell, and then right-click the Reset Button and select Run As Server Control.

    Using an HtmlInputButton control allows you to reset the form fields on the client without a round-trip to the server, while allowing you to manipulate the control on the server side as well, as you’ll do in a later step.

  5. Set the properties of the added controls as follows:

    Control

    Property

    Value

    Label1

    Text

    To:

    Label2

    Text

    CC:

    Label3

    Text

    BCC:

    Label4

    Text

    Subject:

    Label5

    Text

    Body:

    TextBox5

    TextMode

    MultiLine

    TextBox5

    Columns

    60

    TextBox5

    Rows

    10

    Button1

    Text

    Send

    When you’ve finished, the page should look like the following illustration.

    Click To expand
  6. Switch to the code-behind module by double-clicking an empty area of the page. Add an using directive to import the System.Web.Mail namespace so you can refer to its classes without using the namespace name each time. This directive should go at the top of the code-behind module, before the class definition:

    using System.Web.Mail;
  7. Now you need to add code to send the mail when the Send button is clicked. Switch back to SmtpEmail.aspx, and double-click the Send button, which will open the code-behind module for the page and insert a Click event handler for the button, and then add the following code, which creates an instance of the MailMessage class, sets the necessary properties, and then sends the message using the Send method of the SmtpMail class. (Because the Send method is a Static method, it is not necessary to create an instance of SmtpMail to use the method.)

    // Create MailMessage instance, set properties, and sen MailMessage Mail = new MailMessage() Mail.To = TextBox1.Text Mail.Cc = TextBox2.Text Mail.Bcc = TextBox3.Text Mail.Subject = TextBox4.Text Mail.Body = TextBox5.Text // Set the property below to a valid email addres Mail.From = "feedback@aspnetsbs.com" SmtpMail.SmtpServer = "localhost" SmtpMail.Send(Mail) // Use the first label to display statu Label1.Text = "Mail Sent" // Hide the rest of the control TextBox1.Visible = false Label2.Visible = false TextBox2.Visible = false Label3.Visible = false TextBox3.Visible = false Label4.Visible = false TextBox4.Visible = false Label5.Visible = false TextBox5.Visible = false Button1.Visible = false Reset1.Visible = false // Add a Hyperlink control to allow sending another emai HyperLink Link = new HyperLink() Link.Text = "Click here to send another email." Link.NavigateUrl = "SmtpEmail.aspx" // This line is only necessary if the page is in GridLayout mod Link.Attributes["Style"] = "LEFT: 8px; POSITION: absolute; TOP: 50px" Page.Controls.Add(Link);
    

    Once the mail has been sent, the code hides all of the form controls by setting the Visible property for each control to false and adds a HyperLink control to link back to the original page to send another e-mail, if desired. Note that you need to set Mail.From to a valid e- mail address and change SmtpMail.SmtpServer to the name of an available server running SMTP if the local machine is not running an SMTP service.

  8. Save the page and code-behind module, and then build the project. Browse the page by right-clicking SmtpEmail.aspx in Solution Explorer, selecting Browse With, and then selecting Internet Explorer.

    The output should look something like the following illustration. Once you’ve sent e-mail, the link should take you back to the original page.

    Click To expand

This example shows how simple it can be to send e-mail using server controls on a Web Form, but it does have a couple of shortcomings. One is that if you don’t enter an address in the To, CC, or BCC field, you’ll get an error. Another is that it takes a fair amount of code to hide all the controls once you’ve sent the e mail. You can fix this second shortcoming by adding another Label control outside the table, and then turning the table into an HtmlTable control by adding the runat=“server” attribute. You can then hide all of the controls in the table by setting the Visible property of HtmlTable to false.

Registration Wizard

Another common need in Web applications is providing users with an easy way to register. Registration allows you to provide your visitors with personalized services, saved shopping carts, and other valuable assistance. To make registration as simple as possible, you might want to use a multipage format similar to a Windows Wizard interface. This type of interface will be immediately familiar to Windows users. The following listing shows the code for a simple registration wizard implemented as an ASP.NET Web Form. This listing also shows how you can use a single-page structure for controls and code, as opposed to the code-behind structure of Visual Studio .NET. Unlike Web Forms created in Visual Studio .NET, the code in the following listing does not need to be precompiled. However, since the code is included in the page (which must be deployed to the Web server on which it will run), anyone with file access to the Web server can read the code (assuming they have the correct permissions). By contrast, using code-behind modules allows you to deploy just the .aspx files and compiled assembly (or assemblies) without deploying the code-behind modules that contain the UI-related code.

RegWiz.aspx

<%@ Page Language="cs" %> <html> <head> <script runat="server"> void Page_Load(  if (!IsPostBack  Step1.Font.Bold = true   private void Next_Click(object sender, System.EventArgs e  switch (((Button)sender).Parent.ID  case "Page1" Page1.Visible = false Step1.Font.Bold = false Page2.Visible = true Step2.Font.Bold = true break case "Page2" Page2.Visible = false Step2.Font.Bold = false Page3.Visible = true Step3.Font.Bold = true ReviewFName.Text  = "First Name: " + FirstName.Text ReviewMName.Text  = "Middle Name: " + MiddleName.Text ReviewLName.Text  = "Last Name: " + LastName.Text ReviewEmail.Text  = "Email: " + Email.Text ReviewAddress.Text  = "Address: " + Address.Text ReviewCity.Text  = "City: " + City.Text ReviewState.Text  = "State: " + State.Text ReviewZip.Text  = "Zip: " + Zip.Text break   private void Previous_Click(object sender, System.EventArgs e  switch (((Button)sender).Parent.ID  case "Page2" Page2.Visible = false Step2.Font.Bold = false Page1.Visible = true Step1.Font.Bold = true break case "Page3" Page3.Visible = false Step3.Font.Bold = false Page2.Visible = true Step2.Font.Bold = true break   </script> <style type="text/css"> div  {     background:silver;     width:400px;     border:2px outset;     margin:5px;     padding:5px;   </style> </head> <body>    <form runat="server">       <asp:label id="RegWiz" text="Registration Wizard          font-bold="true" font-size="16" font-name="verdana          runat="server"/>       <br/>       <asp:label id="Step1" text="Step 1: Enter Personal Info          font-name="verdana" runat="server"/>       <br/>       <asp:label id="Step2" text="Step 2: Enter Address Info          font-name="verdana" runat="server"/>       <br/>       <asp:label id="Step3" text="Step 3: Review"           font-name="verdana          runat="server"/>       <br/>       <asp:panel id="Page1" runat="server">          <table align="center">             <tr>                <td>                   <asp:label id="FirstNameLabel" text="First Name:                      runat="server"/>                </td>                <td>                  <asp:textbox id="FirstName" runat="server"/>                </td>             </tr>             <tr>                <td>                  <asp:label id="MiddleNameLabel" text="Middle Name:                      runat="server"/>                </td>                <td>                   <asp:textbox id="MiddleName" runat="server"/>                </td>             </tr>             <tr>                <td>                   <asp:label id="LastNameLabel" text="Last Name:                      runat="server"/>                </td>                <td>                   <asp:textbox id="LastName" runat="server"/>                </td>             </tr>             <tr>                <td>                   <asp:label id="EmailLabel" text="Email:                      runat="server"/>                </td>                <td>                   <asp:textbox id="Email" runat="server"/>                </td>             </tr>             <tr>                <td colspan="2" align="center">                   <asp:button id="P1Previous" Text="Previous                      enabled="false" onclick="Previous_Click                      runat="server"/>                   <asp:button id="P1Next" Text="Next                      onclick="Next_Click" runat="server"/>                   <input id="P1Reset" type="reset" runat="server"/>                </td>             </tr>          </table>       </asp:panel>       <asp:panel id="Page2" visible="false" runat="server">          <table align="center">             <tr>                <td>                  <asp:label id="AddressLabel" text="Street Address:                      runat="server"/>                </td>                <td>                   <asp:textbox id="Address" runat="server"/>                </td>             </tr>             <tr>                <td>                   <asp:label id="CityLabel" text="City:                      runat="server"/>                </td>                <td>                   <asp:textbox id="City" runat="server"/>                </td>             </tr>             <tr>                <td>                   <asp:label id="StateLabel" text="State:                      runat="server"/>                </td>                <td>                   <asp:textbox id="State" runat="server"/>                </td>             </tr>             <tr>                <td>                   <asp:label id="ZipLabel" text="Zip Code:                      runat="server"/>                </td>                <td>                   <asp:textbox id="Zip" runat="server"/>                </td>             </tr>             <tr>                <td colspan="2" align="center">                   <asp:button id="P2Previous" Text="Previous                      onclick="Previous_Click" runat="server"/>                   <asp:button id="P2Next" Text="Next                      onclick="Next_Click" runat="server"/>                   <input id="P2Reset" type="reset" runat="server"/>                </td>             </tr>          </table>       </asp:panel>       <asp:panel id="Page3" visible="false" runat="server">          <table align="center">             <tr>                <td colspan="2">                   <asp:label id="ReviewFName" runat="server"/>                </td>             </tr>             <tr>                <td colspan="2">                   <asp:label id="ReviewMName" runat="server"/>                </td>             </tr>             <tr>                <td colspan="2">                   <asp:label id="ReviewLName" runat="server"/>                </td>             </tr>             <tr>                <td colspan="2">                   <asp:label id="ReviewEmail" runat="server"/>                </td>             </tr>             <tr>                <td colspan="2">                   <asp:label id="ReviewAddress" runat="server"/>                </td>             </tr>             <tr>                <td colspan="2">                   <asp:label id="ReviewCity" runat="server"/>                </td>             </tr>             <tr>                <td colspan="2">                   <asp:label id="ReviewState" runat="server"/>                </td>             </tr>             <tr>                <td colspan="2">                   <asp:label id="ReviewZip" runat="server"/>                </td>             </tr>             <tr>                <td colspan="2">                   <asp:button id="P3Previous" Text="Previous                      onclick="Previous_Click" runat="server"/>                  <asp:button id="P3Next" Text="Next" enabled="false                      onclick="Next_Click" runat="server"/>                   <input id="P3Reset" type="reset" disabled="true                      runat="server"/>                </td>                </td>             </tr>          </table>       </asp:panel>    </form> </body> </html>

The keys to the functionality of the registration wizard are the three Panel controls and the Next_Click and Previous_Click event handlers. The Panel controls contain Label, TextBox, and Button Web controls (as well as an HtmlInputButton control for resetting the form fields), which are formatted using standard HTML table elements. When the user clicks the Next button or the Previous button (depending on which one is enabled for that page), the event handlers hide the currently visible panel, show the next (or previous) panel, and update the Label controls that tell the user which step in the process they are on currently.

Since ASP.NET takes care of maintaining the state of the controls from request to request (using ViewState), it is simple to display the data entered by the user on the third panel by simply accessing the Text property of the TextBox controls on the other panels. Notice that the caption text of the controls on the third panel is set declaratively in the tag, and then the text that the user entered is appended to this text programmatically in the event handler using the & operator. The first page of the registration wizard is shown in the illustration on the following page.

Click To expand
Note 

The <style> block defined in RegWiz.aspx takes care of formatting for the Panel controls by defining the desired style for the <div> HTML element. Note that since the Panel control is rendered as a <div> on Internet Explorer and as a <table> element on Netscape and other non–Internet Explorer browsers, you might need to find another way to do the formatting if you want cross- browser compatibility.

One way to accomplish this is through browser sniffing. The Request object exposed by the Page class has a Browser property that provides information on the browser making the current request. By querying the Browser property (and its subproperties), you can perform a simple if statement that links to one style sheet if the browser is Internet Explorer and to another style sheet if it is another browser.

Specialty Controls

In addition to the standard suite of Web controls that provide functionality much like that provided by the Visual Basic GUI controls, ASP.NET offers a set of richer specialty controls that reside in the System.Web.UI.WebControls namespace. Currently these controls include the AdRotator, Calendar, and Xml controls. In this section I’ll describe the purposes of these controls and show some examples.

AdRotator

The AdRotator control is used to display a random selection from a collection of banner advertisements specified in an XML-based advertisement file. The advertisement file contains an <Ad> element for each specified advertisement. This element contains sub-elements that configure the path to the image to display for the ad, the URL to navigate to when the ad is clicked, the text to be displayed when and if the image is not available, the percentage of time the ad should come up in rotation, and any keyword associated with the ad. (You can use keywords to filter ads, allowing the use of a single advertisement file with multiple AdRotator controls and providing each control with different content.)

Note 

The random selection for the AdRotator control will be identical for any AdRotator controls on the page that have identical attributes. You can take advantage of this by using the AdRotator control to display a random selection of header/footer information that you want to be the same for both header and footer.

Use the AdRotator control from a Web Form

  1. Open the Chapter_08 project that you created earlier in this chapter (if it is not already open) and then add a new Web Form to the project. Type the name of the Web Form as AdRotator.aspx.

  2. Change the pageLayout property from GridLayout to FlowLayout.

  3. Switch to HTML view, then add three Label controls and two AdRotator controls between the <form> tags, with the attributes shown in the following code, and then save AdRotator.aspx:

    <asp:label id="title" font-name="Verdana" font-size="18"       text="AdRotator Example" runat="server"/> <br/><br/> <asp:label id="DevLabel" font-name="Verdana" font-size="16"       text="Ad 1" runat="server"/> <br/>  <asp:AdRotator id="AdRotDev" target="_blank" runat="server      advertisementfile="Ads.xml" keywordfilter="Developers"/> <br/><br/> <asp:label id="UserLabel" font-name="Verdana" font-size="16"       text="Ad 2" runat="server"/> <br/>  <asp:AdRotator id="AdRotUsr" target="_blank" runat="server      advertisementfile="Ads.xml" keywordfilter="Users"/>
  4. Create a new XML file by right-clicking the Chapter_08 project in Solution Explorer, selecting Add, then Add New Item, and then choosing XML File as shown in the illustration on the following page. Type the name of the file as Ads.xml.

    Click To expand
  5. Add the following XML to the file, and then save Ads.xml:

    <Advertisements>    <Ad>       <ImageUrl>images/image1.gif</ImageUrl>       <NavigateUrl>http://www.microsoft.com</NavigateUrl>       <AlternateText>Microsoft Main Site</AlternateText>       <Impressions>60</Impressions>       <Keyword>Users</Keyword>    </Ad>    <Ad>       <ImageUrl>images/image2.gif</ImageUrl>       <NavigateUrl>http://msdn.microsoft.com/net</NavigateUrl>       <AlternateText>Microsoft .NET on MSDN</AlternateText>       <Impressions>80</Impressions>       <Keyword>Developers</Keyword>    </Ad>    <Ad>       <ImageUrl>images/image3.gif</ImageUrl>       <NavigateUrl>http://www.microsoft.com</NavigateUrl>       <AlternateText>Microsoft Main Site</AlternateText>       <Impressions>40</Impressions>       <Keyword>Users</Keyword>    </Ad>    <Ad>       <ImageUrl>images/image4.gif</ImageUrl>       <NavigateUrl>http://msdn.microsoft.com/net</NavigateUrl>       <AlternateText>Microsoft .NET on MSDN</AlternateText>       <Impressions>20</Impressions>       <Keyword>Developers</Keyword>    </Ad> </Advertisements>
    
  6. Create a new folder in the project, typing its name as images. Copy the images contained in the images directory of the practice files for Chapter 8 to this new folder.

  7. Save and build the project, and then browse AdRotator.aspx. The output should look similar to the following illustration. When you refresh the page, you should see the ads change randomly, based on the weightings set in the XML file.

    Click To expand

Calendar

The Calendar control is one of the richest and most flexible of the specialized controls, providing nearly 30 properties for controlling the appearance of the calendar. The Calendar control allows you to provide a calendar-based interface for choosing dates or for viewing date-related data.

For example, you could query date data for a series of events or appointments and then use a Calendar control to display them by adding the dates to the calendar’s SelectedDates collection. When a user clicks on a selected date on the calendar, you could then display additional information about the event on that date.

You could also allow users to specify one or more dates for data entry by providing a Calendar control for them to click. The Calendar control supports selection of both single dates and date ranges (by week or month). Using a Calendar control instead of a text box for date entry can help prevent errors in converting the date entered by the user into a Date data type for storage or manipulation.

Create a Web Forms page that uses a Calendar control

  1. Open the Chapter_08 project created earlier in this chapter if it is not already open. Add a new Web Form to the project and type its name as Calendar.aspx.

  2. Change the pageLayout property from GridLayout to FlowLayout.

  3. Switch to HTML view, and use the following code to add three Label controls, two RadioButton controls, two Textbox controls, and a Calendar control between the <form> tags. Note that the GroupName property is used to make the radio buttons mutually exclusive.

    <asp:label id="title" text="Calendar Example"       font-name="Verdana" font-size="18" runat="server"/> <br/> <asp:calendar id="Calendar1" runat="server"/> <br/> <asp:radiobutton id="StartRadio" text="Start Date      groupname="Chooser" runat="server"/> <asp:radiobutton id="EndRadio" text="End Date      groupname="Chooser" runat="server"/> <br/> <asp:label id="StartDateLabel" text="Start Date" runat="server"/> <asp:textbox id="StartDate" runat="server"/> <br/> <asp:label id="EndDateLabel" text="End Date" runat="server"/> <asp:textbox id="EndDate" runat="server"/>
  4. Save the page, then build the project, and then browse the page. The output should look similar to the illustration on the next page.

    Click To expand
  5. Now you need to relate clicking on a date on the calendar to setting the text in the text boxes. Switch back to design view, and then double- click the Calendar control. This will switch to the code-behind module for Calendar.aspx and will add the Calendar1_SelectionChanged event handler. Add the following code to the event handler:

    if (StartRadio.Checked)  StartDate.Text = Calendar1.SelectedDate.ToShortDateString()  else // EndRadio must be checke  EndDate.Text = Calendar1.SelectedDate.ToShortDateString() }
  6. Add the following code to the Page_Load event handler in the code- behind module to take care of initializing the controls:

    if (!IsPostBack  StartRadio.Checked = true Calendar1.SelectedDate = DateTime.Now StartDate.Text = Calendar1.SelectedDate.ToShortDateString() Calendar1.TodaysDate = Calendar1.SelectedDate }
  7. Save the page and code-behind module, and then build the project and browse Calendar.aspx. At this point, you should be able to use the calendar to set the value of both text boxes. Which text box is set depends on which radio button is checked.

  8. At this point the calendar is fairly plain, so let’s use some of the available properties to liven it up a bit. Switch back to Calendar.aspx and modify the <asp:calendar> tag to match the following code. Notice that you need to add a closing </asp:calendar> tag so that you can use the child <titlestyle> tag to set attributes of the calendar’s TitleStyle property.

    <asp:calendar id="Calendar1"      backcolor="lightgray"     borderstyle="groove    borderwidth="5    bordercolor="blue    runat="server">    <titlestyle backcolor="blue" forecolor="silver"        font-bold="true"/> </asp:calendar>
  9. Save and browse the page again. (Because you only changed the .aspx file, you don’t need to rebuild the project.) The output should look similar to the following illustration.

    Click To expand

Xml

The Xml control is a specialty control that lets you display XML code in Web Forms pages. This is important because raw XML within an ASP.NET Web Form will not be displayed predictably. The Xml control can read XML from a string, from a provided URL, or from an object of type System.Xml.XmlDocument.

In addition to simply displaying XML from a given source, the Xml control can apply an XSL Transform document to the XML to perform formatting on the document. The XSL Transform can come from a URL, or it can be provided by an object of type System.Xml.Xsl.XslTransform. The files Xml.aspx and Xml.xslt, included with the practice files for this chapter, show how you can use the Xml control to display the contents of the Ads.xml document in an HTML table.

Validation Controls

Another specialized set of controls that reside in the System.Web.UI.WebControls namespace are the Validation controls, which perform various kinds of validation on other controls. You can use Validation controls to do the following:

  • Ensure that required fields are filled out

  • Ensure that data entered by the user falls within a given range

  • Ensure that data entered by the user matches a specific pattern

  • Compare the values of two controls for a given condition (equality, greater than, and so on) or compare the value of a control to a specified value

  • Ensure that all controls on a page are valid before submitting the page

Shared Members

All Validation controls share a number of important properties and methods. These properties and methods are inherited from the BaseValidator class and include the following:

  • ControlToValidate  This property sets or retrieves a value of type String that specifies the input control to validate.

  • Display  This property sets or retrieves a value that determines how the error message for a Validation control will be displayed. The value must be one of the values specified by the ValidatorDisplay enumeration. The default is Static.

  • EnableClientScript  This property sets or retrieves a Boolean value that determines whether client-side validation will be performed. Server-side validation is always performed with the Validation controls, regardless of this setting. The default is true.

  • Enabled  This property sets or retrieves a Boolean value that determines whether the control is enabled. The default is true.

  • ErrorMessage  This property sets or retrieves a value of type String that specifies the error message to be displayed if the input from the user is not valid.

  • ForeColor  This property sets or retrieves a value of type Color that represents the color of the error message specified in the ErrorMessage property. The default is Color.Red.

  • IsValid  This property sets or retrieves a Boolean value that signifies whether the control specified by the ControlToValidate property passes validation.

  • Validate  This method causes the control on which it is called to perform validation, and it updates the IsValid property with the result.

Table 8-2 lists the Validation controls available in ASP.NET.

Table 8-2: Validation Controls

Control Type

Purpose

Important Members

CompareValidator

Performs validation of a user-entered field with either a constant or another user-entered field. The ControlToCompare and ValueToCompare properties are mutually exclusive. If both are set, the ControlToCompare property takes precedence.

ControlToCompare

This property sets or retrieves a value of type String containing the name of the control whose value will be compared to the value of the control specified by the ControlToValidate property.

Operator

This property sets or retrieves a value that represents the type of comparison to be performed. The value must be one of the values specified by the ValidationCompareOperator enumeration. The default is Equal.

ValueToCompare

This property sets or retrieves a value of type String containing a constant value to which the value of the control specified by the ControlToValidate property will be compared.

CustomValidator

Performs customized validation based on developer- specified logic.

ServerValidate

This event is raised when server-side validation is to be performed. Map the OnServerValidate method in the Validation control tag to the desired server- side event handler to perform custom validation.

ClientValidationFunction

This property sets or retrieves a value of type String containing the name of a client-side function with which to perform client- side validation, if desired.

RangeValidator

Performs validation of a user- entered field to ensure that the value entered is within a specified range.

MaximumValue

This property sets or retrieves a value of type String containing the maximum value of the range to validate against.

MinimumValue

This property sets or retrieves a value of type String containing the minimum value of the range to validate against.

RegularExpressionValidator

Performs validation of a user-entered field to ensure that the value entered matches a specified pattern.

ValidationExpression

This property sets or retrieves a value of type String containing the regular expression to validate against.

RequiredFieldValidator

Performs validation of a user-entered field to ensure that a value is entered for the specified field.

InitialValue

This property sets or retrieves a value of type String containing the initial value of the control to validate against. The default is an empty string. If this property is set to a string value, validation will fail for the control only if the user-entered value matches the value of this property.

ValidationSummary

Provides a summary of validation errors in a given Web Form, either in the Web Form page, a message box, or both.

DisplayMode

This property sets or retrieves a value that determines the way the control will be displayed. The value must be one of the values specified by the ValidationSummaryDisplayMode enumeration. The default is BulletList.

HeaderText

This property sets or retrieves a value of type String containing the header text to be displayed for the validation summary.

ShowMessageBox

This property sets or retrieves a Boolean value that determines whether the validation summary is displayed in a client-side message box. The default is false. This property has no effect if the EnableClientScript property is set to false.

ShowSummary

This property sets or retrieves a Boolean value that determines whether the validation summary is displayed in the Web Form page. The default is true.

Validating Required Fields

To see how the Validation controls operate, let’s return to one of the earlier examples, the Web Form named SmtpEmail.aspx. One of the problems that you had with the page was that if it was submitted without a To, CC, or BCC address, it would throw an exception. You can prevent this problem by requiring at least one To address.

Require data entry with the RequiredFieldValidator control

  1. Open the file SmtpEmail.aspx created earlier in this chapter.

  2. Add a RequiredFieldValidator control to the same table cell as the TextBox1 textbox control and set its properties as follows:

    Control

    Property

    Value

    RequiredFieldValidator1

    ControlToValidate

    TextBox1

    RequiredFieldValidator1

    Display

    Dynamic

    RequiredFieldValidator1

    ErrorMessage

    Required!

  3. Save the page and browse it with Internet Explorer using the Browse With option. (Again, since you have changed only the .aspx file, the project does not need to be rebuilt.) If you do not enter a To address, the output will look something like the following illustration, and you will not be able to submit the page.

    Click To expand

    One problem with this setup is that once you add a To address and submit the page, you might get a JavaScript error. This is because the newly added Validation control is looking for the text box on the client, but since you hid the control in the event handler by setting its Visible property to false, the control no longer exists on the client. You can solve this by modifying how you hide the elements on the page, as you’ll see in the steps that complete this example.

  4. Add a new Label control for your status message. (In the original page, the first label in the table was used for this purpose.) This control should go just before the HTML <table> element.

    <asp:label id="Status" text="" runat="server"/>
  5. Turn the HTML <table> element into an HtmlTable control by adding an id attribute (if necessary, otherwise, just modify the id attribute to match the code snippet that follows) and then switch to design view, right-click the table border, and select Run As Server Control:

    <table id="MailTable" runat="server">
  6. Switch to code view and take out the line of code in the Button1_Click event handler that sets the status message and replace it with the following code:

    // Use the first label to display statu Status.Text = "Mail Sent";
  7. Replace the lines of code in the Button1_Click event handler that set the Visible property of the controls to false with the following lines:

    // Hide the tabl MailTable.Visible = false;
  8. Save the page, browse it, and submit an e-mail. You should no longer get the JavaScript error (and your code’s a lot cleaner to boot).

In addition to using the RequiredFieldValidator to ensure that an e-mail address is entered, you could add a RegularExpressionValidator to each of the addressfields to ensure that the data entered by the user matches the pattern for a valid e mail address. This prevents delivery errors that are due to malformed e-mail addresses and helps prevent the mail server’s resources from being wasted attempting to deliver such mail. A good place to find regular expressions for use with the RegularExpressionValidator control is http://www.regexlib.com/.

Validating by Comparison

Another one of the previous examples with the potential for trouble is the Calendar control example. As coded in the example, the Calendar control can be used to set a start date that is later than the end date. Clearly, if you’re storing these dates or using them to drive some programmatic logic, this is not something you want to allow. Fortunately, the CompareValidator control can help prevent this problem, as illustrated by the following example.

Use the CompareValidator control

  1. Open the file Calendar.aspx created earlier in this chapter.

  2. Add a CompareValidator control below the EndDate TextBox control and set its properties as follows:

    Control

    Property

    Value

    CompareValidator1

    ControlToValidate

    StartDate

    CompareValidator1

    ControlToCompare

    EndDate

    CompareValidator1

    Type

    Date

    CompareValidator1

    Operator

    LessThan

    CompareValidator1

    Display

    Dynamic

    CompareValidator1

    ErrorMessage

    Start Date must be before End Date!

  3. Right-click an empty area of the page and select View Code to switch to the code-behind module, and then add a line of code to the Calendar1_SelectionChanged event handler to cause the Validation control to validate each time the event handler is fired. The Page.Validate call should go just before the closing curly brace of the Calendar1_SelectionChanged function:

    Page.Validate();
  4. Save the file and code-behind module, and then rebuild the project. Browse the page and set the end date to a date earlier than the start date. The validation error message will appear, as shown in the following illustration. Additionally, the IsValid property of the page will be set to false. You can test this property before saving the date values to ensure that they are valid.

    Click To expand

Validation controls can also improve the security of your application. For example, you can use the RegularExpressionValidator control to ensure that passwords entered by users (such as when establishing account information) meet minimum length and complexity requirements. This can make it more difficult for the bad guys to crack your application.

Data-Bound Controls

One of the most significant advances in ASP.NET is in the area of data binding. The System.Web.UI.WebControls namespace contains a set of data-bound controls that offer substantial functionality and flexibility, without the necessity of tying front-end UI logic into back-end database logic, as was the case with the data-bound Design-Time Controls available in classic ASP through the Microsoft Visual InterDev 6.0 development environment. The data-bound controls also allow you to provide data binding regardless of the browser that your clients are using. This is because the controls run on the server and return plain HTML to the client, unlike some of the data-binding techniques that were possible with Internet Explorer versions 4.0 and later.

Another major improvement is that the data-bound controls can use a variety of sources, not just data from a database. Data-bound controls in ASP.NET can be bound to data from an array, an ADO.NET DataSet, a DataView, or any data source that implements the ICollection or IList interfaces. The data-bound controls include the DataGrid, DataList, and Repeater controls. In Chapter 9 you’ll learn more about these controls.


Team LiB
Previous Section Next Section


JavaScript EditorJavascript debugger     Javascript examples