Simple Controls

The simple controls are so named because most emit only a few lines of HTML. Some return client-side script too, but only under special circumstances. They鈥檙e exceedingly easy to use, and thus are a great starting point for an exploration of Web controls.

TextBox Controls

TextBox controls are the ASP.NET equivalent of <input type=鈥渢ext/password鈥?gt; and <textarea> tags in HTML. Their purpose? To create text input fields in Web forms. The statement

<asp:TextBox聽ID="UserName" RunAt="server" />

creates a text input field in a Web form and assigns it the programmatic ID 鈥淯serName鈥? You can use a TextBox鈥檚 Text property to declaratively insert text into a TextBox and also to read and write TextBox text from a server-side script. The following statement creates a TextBox that initially contains the string 鈥淓lmo鈥?

<asp:TextBox聽ID="UserName" Text="Elmo" RunAt="server" />

And the following server-side script reads the contents of the TextBox:

string聽name聽=聽UserName.Text;

Text is one of several public properties that the TextBox class exposes. Others include Rows and Columns, which size a TextBox by setting the number of rows and columns that it displays; MaxLength, which limits the number of characters a TextBox will accept; ReadOnly, which, when true, prevents the TextBox from accepting input; Wrap, which determines whether text wraps in a multiline TextBox; and TextMode, which can be set to SingleLine (the default) to create single-line input fields, MultiLine to create multiline input fields, or Password to create password input fields鈥攆ields that display asterisks or other characters in place of the actual characters that the user types. The following statement creates a password input field named 鈥淧assword鈥?

<asp:TextBox聽ID="Password" TextMode="Password" RunAt="server" />

To create a multiline input field, set TextMode to MultiLine and Rows to the number of rows you want the TextBox to display:

<asp:TextBox聽ID="Comments" TextMode="MultiLine" Rows="10"
聽聽RunAt="server" />

The Rows attribute is ignored unless you explicitly set TextMode to MultiLine.

A TextBox renders itself as an <input type=鈥渢ext鈥?gt;, <input type=鈥減assword鈥?gt;, or <textarea> tag, depending on the value assigned to its TextMode property. Here are three <asp:TextBox> tags and the HTML that they produce:

//聽Before
<asp:TextBox聽ID="UserName" RunAt="server" />
<asp:TextBox聽ID="Password" TextMode="Password" RunAt="server" />
<asp:TextBox聽ID="Comments" TextMode="MultiLine" Rows="10"
聽聽RunAt="server" />

//聽After
<input聽name="UserName" type="text" id="UserName" />
<input聽name="Password" type="password" id="Password" />
<textarea聽name="Comments" rows="10" id="Comments"></textarea>

Examining the HTML that Web controls return is a great way to get acquainted with Web controls and learn more about how they work.

TextChanged Events and the AutoPostBack Property

TextBox controls fire TextChanged events following a postback if the text inside them has changed. An OnTextChanged attribute in an <asp:TextBox> tag designates a handler for TextChanged events:

<asp:TextBox聽ID="UserName" OnTextChanged="OnNameChanged"
聽聽RunAt="server" />
聽聽聽聽.
聽聽聽聽.
聽聽聽聽.
<script聽language="C#" runat="server">
聽聽void聽OnNameChanged聽(Object聽sender,聽EventArgs聽e)
聽聽{
聽聽聽聽聽聽//聽Name聽changed;聽read聽it聽from聽the聽TextBox
聽聽聽聽聽聽string聽name聽=聽UserName.Text;
聽聽}
</script>

TextChanged events fire only when the page posts back to the server. By default, TextBox controls don鈥檛 generate postbacks themselves and therefore fire TextChanged events only when another control on the page forces a postback. However, you can set a TextBox control鈥檚 AutoPostBack property to true to force postbacks to occur (and TextChanged events to fire) the moment the text inside the control changes:

<asp:TextBox聽ID="UserName" OnTextChanged="OnNameChanged"
聽聽AutoPostBack="true" RunAt="server" />

Unlike Windows edit controls, which fire EN_CHANGE notifications in response to each and every character that the user enters, TextBox controls with AutoPostBack enabled fire TextChanged events only when they lose the input focus (that is, when the user moves to another control in the Web page) following a text change. That鈥檚 good, because a page that posts back to the server every time a character is entered into a TextBox would be a slow page indeed.

How does setting AutoPostBack to true cause postbacks to occur when a TextBox loses the input focus? With a sprinkle of JavaScript and a dash of Dynamic HTML (DHTML). Enter this statement into a Web form:

<asp:TextBox聽ID="UserName" AutoPostBack="true" RunAt="server" />

and the control outputs this:

<input聽name="UserName" type="text" id="UserName"
聽聽onchange="__doPostBack('UserName','')" language="javascript" />
聽聽聽聽.
聽聽聽聽.
聽聽聽聽.
<script聽language="javascript">
<!--
聽聽function聽__doPostBack(eventTarget,聽eventArgument)聽{
聽聽聽聽聽聽var聽theform聽=聽document.ctl0;
聽聽聽聽聽聽聽聽.
聽聽聽聽聽聽聽聽.
聽聽聽聽聽聽聽聽.
聽聽聽聽聽聽theform.submit();
聽聽}
//聽-->
</script>

The <input> tag includes an onchange attribute that activates a JavaScript function named __doPostBack on the client when the control loses the input focus following a text change. The __doPostBack function programmatically posts the page back to the server by calling the Submit method of the DHTML object that represents the form.

TextBox isn鈥檛 the only Web control that features an AutoPostBack property; CheckBox, RadioButton, and several other controls support it as well. Whenever AutoPostBack appears in a control鈥檚 property list, setting it to true causes postbacks to occur (and events to fire) the moment a change occurs in the state of the control. Otherwise, the control鈥檚 events won鈥檛 fire until an external stimulus forces a postback.

Label Controls

Label controls are among the simplest鈥攊f not the simplest鈥攐f all Web controls. They add programmable textual labels to Web forms. A Label control鈥檚 Text property exposes the control text. The following statement adds 鈥淗ello鈥?to a Web page:

<asp:Label聽Text="Hello" RunAt="server" />

A Label control declared this way renders itself to the Web page as a <span> tag:

<span>Hello</span>

Spans are benign HTML tags that are used to group other HTML elements.

Label controls frequently serve as placeholders for output written by server-side scripts. The following statement declares an empty Label control and assigns it the programmatic ID 鈥淥utput鈥?

<asp:Label聽ID="Output" RunAt="server" />

And this statement in a server-side script writes 鈥淗ello鈥?to the Web page where the Label control is positioned:

Output.Text聽= "Hello";

Use a Label control whenever you want to add text to a Web page and change that text from a server-side script. For static labels, use ordinary HTML text instead. Static HTML text improves performance by preventing ASP.NET from having to instantiate and execute a control each time the page is requested from the server.

HyperLink Controls

HyperLink controls add hyperlinks to Web forms. HyperLink controls come in two forms: text hyperlinks and image hyperlinks. The following statement creates a hyperlink that renders itself as a text string and points to www.wintellect.com:

<asp:HyperLink聽Text="Click聽here"
聽聽NavigateUrl="http://www.wintellect.com" RunAt="server" />

A slight modification transforms the hyperlink into an image that targets the same URL:

<asp:HyperLink聽ImageUrl="logo.jpg"
聽聽NavigateUrl="http://www.wintellect.com" RunAt="server" />

Text hyperlinks render as <a href> tags; image hyperlinks render as <img> tags enclosed in <a href> tags. You normally include either a Text or an ImageUrl attribute in an <asp:HyperLink> tag, but not both. However, if you do specify both, the control uses the text you specify as a tool tip in supportive browsers.

The HyperLink class exposes a Target property that can be used to control how the targeted Web page is displayed. For example, the statement

<asp:HyperLink聽Text="Click聽here" Target="_new"
聽聽NavigateUrl="http://www.wintellect.com" RunAt="server" />

opens the page in a new browser window. Any value that鈥檚 valid for a Target attribute in an <a> tag is also valid in a HyperLink. Another use for Target attributes is to open pages in specific windows or frames.

Like Label controls, HyperLink controls should be used only when you want to change the properties of the control dynamically鈥攖hat is, when ordinary <a href> tags won鈥檛 do. The following code initializes the target of a hyperlink when the page loads:

<asp:HyperLink聽ID="MyLink" Text="Web聽page聽du聽jour" RunAt="server" />
聽聽.
聽聽.
聽聽.
<script聽language="C#" runat="server">
聽聽void聽Page_Load聽(Object聽sender,聽EventArgs聽e)
聽聽{
聽聽聽聽聽聽MyLink.NavigateUrl聽= "www.wintellect.com";
聽聽}
</script>

One motivation for initializing a HyperLink control in this way is to retrieve the targeted URL from a database or an XML file.

Image Controls

Image controls add images to Web forms by emitting <img> tags. Image鈥檚 most important properties are ImageUrl, which specifies the URL of the image that the control renders; ImageAlign, which controls the alignment of the image; and AlternateText, which specifies the image鈥檚 alternate text. Alternate text is displayed in place of the image in text-only browsers. The following statement declares an Image control in a Web form:

<asp:Image聽ImageUrl="logo.jpg" AlternateText="Company聽Logo"
聽聽RunAt="server" />

Image controls are perfect for displaying images whose URLs are assigned at run time, possibly in response to user input. For static images, you can reduce overhead by using conventional <img> tags instead.

CheckBox Controls

CheckBox controls place check boxes in Web forms. (Surprise!) A CheckBox鈥檚 Checked property determines whether the check box is checked (true) or unchecked (false), and its Text property controls the text displayed beside the check box. The following code declares a CheckBox control in a Web form:

<asp:CheckBox聽ID="Confirm" Text="E-mail聽my聽confirmation"
聽聽RunAt="server" />

And this server-side script determines whether the check box is checked when the form is submitted to the server:

if聽(Confirm.Checked)聽{
聽聽聽聽//聽The聽box聽is聽checked
}
else聽{
聽聽聽聽//聽The聽box聽is聽not聽checked
}

On the off chance that you鈥檇 like to reverse the positions of a check box and the text that normally appears to its right, include a TextAlign=鈥淟eft鈥?attribute in the control tag.

CheckBox controls fire CheckedChanged events when they鈥檙e checked and unchecked. By default, a CheckedChanged event doesn鈥檛 fire the moment the check box is clicked; it waits until the page posts back to the server. To respond immediately to changes in a check box鈥檚 state, set the control鈥檚 AutoPostBack property to true to force postbacks:

<asp:CheckBox聽ID="Confirm" Text="E-mail聽my聽confirmation"
聽聽AutoPostBack="true" OnCheckedChanged="DoItNow" RunAt="server" />
聽聽聽聽.
聽聽聽聽.
聽聽聽聽.
<script聽language="C#" runat="server">
聽聽void聽DoItNow聽(Object聽sender,聽EventArgs聽e)
聽聽{
聽聽聽聽聽聽//聽The聽check聽box聽was聽just聽checked聽or聽unchecked;聽do聽something!
聽聽}
</script>

Don鈥檛 set AutoPostBack to true unless you really need CheckedChanged events to fire immediately. One justification for setting AutoPostBack to true is to dynamically change the contents of the page each time the check box is clicked.

RadioButton Controls

RadioButton controls create radio buttons in Web forms. Radio buttons present users with mutually exclusive lists of choices. Clicking a radio button checks that radio button and unchecks other radio buttons in the group.

RadioButton derives from CheckBox and therefore supports the same properties and events that CheckBox supports. It also adds a GroupName property for designating the group that a radio button belongs to. The following code declares five RadioButton controls and divides them into two groups: one group of three and another group of two. It also uses the RadioButton.Checked property to check the first radio button in each group:

<asp:RadioButton聽Text="Red" ID="Button1" Checked="true"
聽聽GroupName="Colors" RunAt="server" /><br>
<asp:RadioButton聽Text="Green" ID="Button2"
聽聽GroupName="Colors" RunAt="server" /><br>
<asp:RadioButton聽Text="Blue" ID="Button3"
聽聽GroupName="Colors" RunAt="server" /><br>
<br>
<asp:RadioButton聽Text="Circle" ID="Button4" Checked="true"
聽聽GroupName="Shape" RunAt="server" /><br>
<asp:RadioButton聽Text="Square" ID="Button5"
聽聽GroupName="Shape" RunAt="server" />

Grouping these controls by using the GroupName attribute is important because it tells the browser which radio buttons to uncheck when a radio button is checked.

Figuring out which radio button in a group of radio buttons is checked from a server-side script requires checking each button鈥檚 Checked property one by one. A better way to add radio buttons to a Web page is to use a RadioButtonList. Its SelectedIndex property identifies the button that鈥檚 checked. RadioButtonList also simplifies the task of arranging radio buttons on a page. You鈥檒l learn all about RadioButtonList later in this chapter.

Table Controls

Table controls add HTML tables to Web forms. They render a combination of <table>, <tr>, and <td> tags to browsers. Here鈥檚 one way to add a table to a Web form:

<table>
聽聽<tr>
聽聽聽聽<td>Row聽1,聽Column聽1</td>
聽聽聽聽<td>Row聽1,聽Column聽2</td>
聽聽</tr>
聽聽<tr>
聽聽聽聽<td>Row聽2,聽Column聽1</td>
聽聽聽聽<td>Row聽2,聽Column聽2</td>
聽聽</tr>
</table>

And here鈥檚 the equivalent table created with a Table control:

<asp:Table聽ID="MyTable" RunAt="server">
聽聽<asp:TableRow>
聽聽聽聽<asp:TableCell>Row聽1,聽Column聽1</asp:TableCell>
聽聽聽聽<asp:TableCell>Row聽1,聽Column聽2</asp:TableCell>
聽聽</asp:TableRow>
聽聽<asp:TableRow>
聽聽聽聽<asp:TableCell>Row聽2,聽Column聽1</asp:TableCell>
聽聽聽聽<asp:TableCell>Row聽2,聽Column聽2</asp:TableCell>
聽聽</asp:TableRow>
</asp:Table>

Table controls add value to a Web form when you want to change a table鈥檚 contents dynamically. For example, the following server-side script modifies the text in each of the table cells:

MyTable.Rows[0].Cells[0].Text聽= "Cell聽1";
MyTable.Rows[0].Cells[1].Text聽= "Cell聽2";
MyTable.Rows[1].Cells[0].Text聽= "Cell聽3";
MyTable.Rows[1].Cells[1].Text聽= "Cell聽4";

This script builds the entire table at run time:

<asp:Table聽ID="MyTable" RunAt="server" />
聽聽.
聽聽.
聽聽.
<script聽language="C#" runat="server">
聽聽void聽Page_Load聽(Object聽sender,聽EventArgs聽e)
聽聽{
聽聽聽聽聽聽for聽(int聽i=0;聽i<2;聽i++)聽{
聽聽聽聽聽聽聽聽聽聽TableRow聽row聽=聽new聽TableRow聽();
聽聽聽聽聽聽聽聽聽聽for聽(int聽j=0;聽j<2;聽j++)聽{
聽聽聽聽聽聽聽聽聽聽聽聽聽聽TableCell聽cell聽=聽new聽TableCell聽();
聽聽聽聽聽聽聽聽聽聽聽聽聽聽cell.Text聽=聽String.Format聽("Row聽{0},聽Column聽{1}",
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽i聽+聽1,聽j聽+聽1);
聽聽聽聽聽聽聽聽聽聽聽聽聽聽row.Cells.Add聽(cell);
聽聽聽聽聽聽聽聽聽聽}
聽聽聽聽聽聽聽聽聽聽MyTable.Rows.Add聽(row);
聽聽聽聽聽聽}
聽聽}
</script>

These scripts work because a Table object exposes the rows that it contains through a property named Rows. Each row in the Rows collection is an instance of TableRow. Within a row, each cell is represented as a TableCell object that鈥檚 accessible through the row鈥檚 Cells collection. Calling Add on a Rows or Cells collection programmatically adds a row to a table or a cell to a row.

By default, a Table control鈥檚 borders are invisible. You can change that by setting the control鈥檚 GridLines property to Horizontal, Vertical, or Both. Other useful Table properties include CellPadding and CellSpacing, which, like the HTML attributes of the same name, control the spacing within and between cells, and BackImageUrl, which identifies a background image. Tables are often used in Web pages to paint colored backgrounds. To change a Table object鈥檚 background color, use the BackColor property that Table inherits from WebControl.

Panel Controls

Panel controls serve as containers for other controls. One use for Panel controls is to control the visibility of a group of controls. The following Web form toggles four Label controls on and off by setting a Panel control鈥檚 Visible property to true or false each time a check box is clicked. Note the AutoPostBack=鈥渢rue鈥?attribute in the <asp:CheckBox> tag:

<html>
聽聽<body>
聽聽聽聽<form聽runat="server"><br>
聽聽聽聽聽聽<asp:CheckBox聽ID="Toggle" Text="Show聽Labels" Checked="true"
聽聽聽聽聽聽聽聽AutoPostBack="true" OnCheckedChanged="OnToggle"
聽聽聽聽聽聽聽聽RunAt="server" />
聽聽聽聽聽聽<asp:Panel聽ID="MyPanel" RunAt="server">
聽聽聽聽聽聽聽聽<asp:Label聽Text="John" RunAt="server" /><br>
聽聽聽聽聽聽聽聽<asp:Label聽Text="Paul" RunAt="server" /><br>
聽聽聽聽聽聽聽聽<asp:Label聽Text="George" RunAt="server" /><br>
聽聽聽聽聽聽聽聽<asp:Label聽Text="Ringo" RunAt="server" /><br>
聽聽聽聽聽聽</asp:Panel>
聽聽聽聽</form>
聽聽</body>
</html>

<script聽language="C#" runat="server">
聽聽void聽OnToggle聽(Object聽sender,聽EventArgs聽e)
聽聽{
聽聽聽聽聽聽MyPanel.Visible聽=聽Toggle.Checked;
聽聽}
</script>

Another use for Panel controls is to specify horizontal alignment for a group of controls:

<asp:Panel聽HorizontalAlign="Center" ID="MyPanel" RunAt="server">
聽聽<asp:Label聽Text="John" RunAt="server" /><br>
聽聽<asp:Label聽Text="Paul" RunAt="server" /><br>
聽聽<asp:Label聽Text="George" RunAt="server" /><br>
聽聽<asp:Label聽Text="Ringo" RunAt="server" /><br>
</asp:Panel>

Panel controls render as HTML <div> tags. Therefore, it鈥檚 appropriate to use them any time you would ordinarily use a <div> tag but want to change the attributes of that tag dynamically.