O'Reilly logo

Programming ASP .NET by Dan Hurwitz, Jesse Liberty

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 4. Controls

Controls are the building blocks of a graphical user interface. Familiar controls include buttons, checkboxes, list boxes, and so forth. Controls can provide a means for a user to indicate a preference, enter data, or make selections.

There are five types of web controls; each but the first will be covered in detail in this and coming chapters. They are:

HTML controls

The original controls available to any HTML page. These all work in ASP.NET exactly as they work in other web pages. HTML controls will be used where appropriate in this book, but will not be discussed in detail. For a good resource on HTML controls, see HTML: The Definitive Guide ,by Chuck Musciano and Bill Kennedy (O’Reilly).

HTML server controls

Based on original HTML controls, but enhanced to enable server-side processing.

Web (ASP) server controls

Server-side controls providing the same functionality as HTML server controls but integrated into the ASP.NET programming model.

Validation controls

Provide a full range of built-in form validation capability. Validation controls are covered in Chapter 8.

User controls and custom controls

Controls created by the developer. User and custom controls are covered in Chapter 14.

HTML server controls and ASP controls both offer significant improvements over the old-style HTML controls. These include:

  • The ability to automatically maintain state, covered in detail in Chapter 6.

  • Browser independence. ASP.NET detects the level of the target browser. Up-level DHTML browsers are sent script for client-side processing. On downlevel standard browsers, all processing is done on the server. The appropriate HTML is generated for each browser.

  • Use of a compiled language instead of interpreted script, resulting in better performance.

  • The ability to bound HTML server controls and ASP controls to a data source, as discussed in Chapter 9.

HTML Server Controls

Normal HTML controls such as <h1>, <a>, and <input> are not processed by the server, but are sent directly to the browser for display. Standard HTML controls can be exposed to the server and made available for server-side processing by turning them into HTML server controls. Server-side processing allows for data binding, programmatic response to events, and the ability to use a fully featured and compiled coding language rather than a scripting language.

In order to convert an HTML control to an HTML server control, simply add the attribute runat="server". In addition, you will probably want to add an id attribute, so that contents of the control can be accessed and controlled programmatically. If you start with a simple input control:

<input type="text" size="40">

you can convert it to an HTML server control by adding the id and runat attributes, as follows:

<input type="text" id="BookTitle" size="40" runat="server">

There are several benefits to converting an HTML control to an HTML server control:

  • Once a control is converted to a server control, it can be referred to in code. For example, in Example 4-1 and Example 4-2 you can read or set the value of the text box by referring to lblBookName.Value or txtBookName.Value.

  • Server controls retain state during round trips to the server (more on this in Chapter 6).

  • Server controls generate events, which your code can then handle.

  • Server controls are aware of the client browser level and generate HTML appropriate to the target browser.

Example 4-1 and Example 4-2 demonstrate the use of HTML server controls in C# and VB.NET, respectively. In these listings, a text box is used to prompt the user to enter a book name. When the Button control is clicked, it fires an event that fills a second text box with the contents of the first text box and also changes its size.

Example 4-1. Code listing for csHTMLServerControls.aspx

               <%@ Page Language="C#" %>
<html>

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

   <body>
   <form runat=server>

      <h1>HTML Server Controls</h1>

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

      <br/>

      <h2>HTML Server Control</h2>
      Book Name:&nbsp;&nbsp;&nbsp;
      <input type="text" 
         id="txtBookName" 
         size="40" 
         value="Enter book name."
         runat="server" />

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

      <input type="submit" 
         id="btnBookName" 
         value="Book Name" 
         onServerClick="btnBookName_Click" 
         runat="server" />
      <br/>
      <br/>
      <input type="text" id="lblBookName" size="40" runat="server" />

   </form>
   </body>
</html>

Example 4-2. Code listing for vbHTMLServerControls.aspx

               <%@ Page Language="VB" %>
<html>

<script runat="server">
   Sub btnBookName_Click(ByVal Sender as Object, _
                         ByVal e as EventArgs)
   
      lblBookName.Value = txtBookName.Value
      lblBookName.Size = 80
   End Sub
</script>

   <body>
   <form runat=server>

      <h1>HTML Server Controls</h1>

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

      <br/>

      <h2>HTML Server Control</h2>
      Book Name:&nbsp;&nbsp;&nbsp;
      <input type=text 
         id="txtBookName" 
         size="40" 
         value="Enter book name."
         runat="server" />

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

      <input type="submit" 
         id="btnBookName" 
         value="Book Name" 
         onServerClick="btnBookName_Click" 
         runat="server" />

      <br/>
      <br/>
      <input type="text" id="lblBookName" size="40" runat="server"/>

   </form>
   </body>
</html>

The very first line of code in both listings:

            
<%@ Page Language="C#" %>

<%@ Page Language="VB" %>

is a page directive, which tells the compiler that any script found in this page is written using the C# or VB language, respectively. Immediately following the opening <HTML> tag in Example 4-1 and Example 4-2 is a script block, written in C# or VB.NET, respectively, as indicated by the page directive. It contains a routine called btnBookName_Click, which is the event handler for the Click event of the btnBookName button. This method takes two parameters and returns nothing (as indicated by the void keyword in C# and the Sub keyword in VB.NET). These parameters are typical for all event handler methods in ASP.NET, as discussed in Chapter 3. In C# the parameter list is of the form:

            
 (Object Source, EventArgs E)

and in VB.NET:

            
 (ByVal Sender as Object, ByVal e as EventArgs)

Note that within the body of the routine, the HTML server controls are referred to by their id attribute, for example lblBookName and txtBookName.

The Submit button:

            
<input type="submit" 

is prototypical of converting HTML controls to server controls. It has an id attribute and the runat attribute:

            
id="btnBookName"
runat="server"

Rather than the traditional onClick attribute used in conventional HTML or ASP pages, the Submit button has an onServerClick attribute, telling the server what function to call when the Click event occurs:

            
onServerClick="btnBookName_Click" 

Tip

If you want the control to handle the event on the client side, you should use the onClick attribute. In this case, you must provide client-side scripting to handle the event. You cannot have both an onClick and onServerClick attribute for the same control.

Figure 4-1 shows the page that results from running the code in either Example 4-1 or Example 4-2, filling in a book name, and clicking the Book Name button.

Output from Example 4-1 or Example 4-2

Figure 4-1. Output from Example 4-1 or Example 4-2

HTML controls are divided into two categories: input and container. HTML input controls do not require a closing tag (although to be well-formed, they should be made self-closing with a trailing /) and have Name, Value, and Type attributes, which may be accessed and controlled programmatically.

HTML container controls are required to have either a trailing / or a closing tag. They do not have Name, Value, or Type attributes. Instead, the content found between opening and closing tags may be accessed programmatically using the InnerHtml or InnerText property. The difference between these two properties is that InnerText provides automatic HTML encoding and decoding of special characters, such as < or >. If the InnerHtml property is used, these characters are interpreted as being part of the HTML and will not display in the final output.

Example 4-3 and Example 4-4 show both input controls and HTML server container controls in C# and VB.NET, respectively, and demonstrate the use of the InnerHtml property.

Example 4-3. Input and container HTML server controls using C#, csHTMLServerControls2.aspx

<%@ Page Language="C#" %>

<script runat="server">
   void Page_Load(Object Source, EventArgs E)
   {
      string strHtml = "";
      strHtml += txtName.Value + "<br/>";
      strHtml += txtStreet.Value + "<br/>";
      strHtml += txtCity.Value + ", " + txtState.Value;
      tdInnerHtml.InnerHtml = strHtml;
   }
</script>

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

      <h1>HTML Server Controls</h1>
      <h2>InnerHTML</h2>

      <table>
         <tr>
            <td>Name:</td>
            <td>
                <input type="text"
                    id="txtName"
                     runat="server"/>
            </td>
         </tr>
         <tr>
            <td>Street:</td>
            <td>
                <input type="text"
                    id="txtStreet"
                     runat="server"/>
            </td>
         </tr>
         <tr>
            <td>City:</td>
            <td>
                <input type="text"
                    id="txtCity"
                     runat="server"/>
            </td>
         </tr>
         <tr>
            <td>State:</td>
            <td>
                <input type="text"
                    id="txtState"
                     runat="server"/>
            </td>
         </tr>
         <tr>
            <td></td>
            <td id="tdInnerHtml" runat="server" />
         </tr>
      </table>

      <input type=submit value="Do It!">

    </form>
   </body>
</html>

Example 4-4. Input and container HTML server controls using VB.NET, vbHTMLServerControls2.aspx

<%@ Page Language="VB" %>

<script runat="server">
   sub Page_Load(ByVal Sender as Object, _
                 ByVal e as EventArgs)
      dim strHtml as string
      strHtml = txtName.Value & "<br/>"
      strHtml = strHtml & txtStreet.Value & "<br/>"
      strHtml = strHtml & txtCity.Value & ", " & txtState.Value
      tdInnerHtml.InnerHtml = strHtml
   end sub
</script>

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

      <h1>HTML Server Controls</h1>
      <h2>InnerHTML</h2>

      <table>
         <tr>
            <td>Name:</td>
            <td>
                <input type="text"
                    id="txtName"
                     runat="server"/>
            </td>
         </tr>
         <tr>
            <td>Street:</td>
            <td>
                <input type="text"
                    id="txtStreet"
                     runat="server"/>
            </td>
         </tr>
         <tr>
            <td>City:</td>
            <td>
                <input type="text"
                    id="txtCity"
                     runat="server"/>
            </td>
         </tr>
         <tr>
            <td>State:</td>
            <td>
                <input type="text"
                    id="txtState"
                     runat="server"/>
            </td>
         </tr>
         <tr>
            <td></td>
            <td id="tdInnerHtml" runat="server" />
         </tr>
      </table>

      <input type=submit value="Do It!">

    </form>
   </body>
</html>

In Example 4-3 and Example 4-4, there are two types of input controls: text fields and a button. Both happen to use the <input> HTML tag, although as you can see in Table 4-1, there are other input controls that do not use those tags.

Table 4-1. HTML tags and theircategories

HTML tag

Category

HTML server control name

Description

<input>

Input

HtmlInputButton

HtmlInputCheckBox

HtmlInputFile

HtmlInputHidden

HtmlInputImage

HtmlInputRadioButton

HtmlInputText

<input type=button | submit | reset>

<input type=checkbox>

<input type=file>

<input type=hidden>

<input type=image>

<input type=radio>

<input type=text | password>

<img>

Input

HtmlImage

Image

<textarea>

Input

HtmlTextArea

Multiline text entry

<a>

Container

HtmlAnchor

Anchor

<button>

Container

HtmlButton

Customizable output format, usable with IE 4.0 and above browsers

<form>

Container

HtmlForm

Maximum of one HtmlForm control per page; default method is POST

<table>

Container

HtmlTable

Table, which can contain rows, which can contain cells

<td>

<th>

Container

HtmlTableCell

Table cell

Table header cell

<tr>

Container

HtmlTableRow

Table row

<select>

Container

HtmlSelect

Pull-down menu of choices

Container

HtmlGenericControl

Any HTML control not listed here

The table, which is a container control, is used in these examples primarily as a means of controlling the layout of the other controls on the page. It has not been converted to an HTML server control, since it does not have the runat="server" attribute. One of the cells, however, has been converted for server-side processing by the inclusion of that attribute. In addition, that cell has an id attribute so that it can be referred to programmatically in the Page_Load routine.

Looking at the Page_Load routine, which is executed every time the page is posted, i.e., every time the Do It! button is clicked, an HTML string is constructed containing the values of the input text fields, interspersed with some HTML to control line breaks. This string is then assigned to the InnerHtml property of the table cell with the tdInnerHtml id attribute:

            
tdInnerHtml.InnerHtml = strHtml

If the InnerText property is used instead of the InnerHtml property, then the resulting page would display the actual < and > symbols. As written, however, the resulting page will look something like Figure 4-2, after values are entered in the text fields and the button is clicked.

Output from Example 4-3 or 4-4

Figure 4-2. Output from Example 4-3 or 4-4

Table 4-1 lists HTML tags and the category to which they belong.

Tip

You never actually use the name of HTML server control shown in Table 4-1 in any of your code. What goes in your HTML code is the HTML tag with the addition of the runat="server" attribute and usually with the addition of an id attribute.

Actually, any HTML control can be converted to server-side processing with the addition of the runat="server" attribute. If the control is not listed in Table 4-1, then it will be treated as an HtmlGenericControl. As with any other container control, this allows programmatic access to the control’s inner HTML.

All the HTML server controls derive from the System.Web.UI.Control class and are contained in the System.Web.UI.HTMLControls namespace. Figure 4-3 shows the HTML server control hierarchy.

The HTML server control object hierarchy

Figure 4-3. The HTML server control object hierarchy

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required