In this chapter, you learn how to use the core controls contained in the ASP.NET 2.0 Framework. These are controls that you’ll use in just about any ASP.NET application that you build.
You learn how to display information to users by using the Label
and Literal
controls. You learn how to accept user input with the TextBox
, CheckBox
, and RadioButton
controls. You also learn how to submit forms with the button controls.
At the end of this chapter, you learn how to group form fields with the Panel
control. Finally, you learn how to link from one page to another with the HyperLink
control.
The ASP.NET Framework includes two controls you can use to display text in a page: the Label
control and the Literal
control. Whereas the Literal
control simply displays text, the Label
control supports several additional formatting properties.
Whenever you need to modify the text displayed in a page dynamically, you can use the Label
control. For example, the page in Listing 2.1 dynamically modifies the value of a Label
control’s Text
property to display the current time (see Figure 2.1).
Example 2.1. ShowLabel.aspx
<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> Sub Page_Load() lblTime.Text = DateTime.Now.ToString("T") End Sub </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Show Label</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label id="lblTime" Runat="server" /> </div> </form> </body> </html>
Any string that you assign to the Label
control’s Text
property is displayed by the Label
when the control is rendered. You can assign simple text to the Text
property or you can assign HTML content.
As an alternative to assigning text to the Text
property, you can place the text between the Label
control’s opening and closing tags. Any text that you place before the opening and closing tags gets assigned to the Text
property.
By default, a Label
control renders its contents in an HTML <span>
tag. Whatever value you assign to the Text
property is rendered to the browser enclosed in a <span>
tag.
The Label
control supports several properties you can use to format the text displayed by the Label
(this is not a complete list):
BackColor
—. Enables you to change the background color of the label.
BorderColor
—. Enables you to set the color of a border rendered around the label.
BorderStyle
—. Enables you to display a border around the label. Possible values are NotSet
, None
, Dotted
, Dashed
, Solid
, Double
, Groove
, Ridge
, Inset
, and Outset
.
BorderWidth
—. Enables you to set the size of a border rendered around the label.
CssClass
—. Enables you to associate a Cascading Style Sheet class with the label.
Font
—. Enables you to set the label’s font properties.
ForeColor
—. Enables you to set the color of the content rendered by the label.
Style
—. Enables you to assign style attributes to the label.
ToolTip
—. Enables you to set a label’s title
attribute. (In Microsoft Internet Explorer, the title
attribute is displayed as a floating tooltip.)
In general, I recommend that you avoid using the formatting properties and take advantage of Cascading Style Sheets to format the rendered output of the Label
control. The page in Listing 2.2 contains two Label
controls: The first is formatted with properties and the second is formatted with a Cascading Style Sheet (see Figure 2.2).
Example 2.2. FormatLabel.aspx
<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <style type="text/css"> div { padding:10px; } .labelStyle { color:red; background-color:yellow; border:Solid 2px Red; } </style> <title>Format Label</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label id="lblFirst" Text="First Label" ForeColor="Red" BackColor="Yellow" BorderStyle="Solid" BorderWidth="2" BorderColor="red" Runat="server" /> <br /><br /> <asp:Label id="lblSecond" Text="Second Label" CssClass="labelStyle" Runat="server" /> </div> </form> </body> </html>
You should use a Label
control when labeling the fields in an HTML form. The Label
control includes a property named the AssociatedControlID
property. You can set this property to point at an ASP.NET control that represents a form field.
For example, the page in Listing 2.3 contains a simple form that contains fields for entering a first and last name. Label controls are used to label the two TextBox
controls.
Example 2.3. LabelForm.aspx
<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Label Form</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label id="lblFirstName" Text="First Name:" AssociatedControlID="txtFirstName" Runat="server" /> <br /> <asp:TextBox id="txtFirstName" Runat="server" /> <br /><br /> <asp:Label id="lblLastName" Text="Last Name:" AssociatedControlID="txtLastName" Runat="server" /> <br /> <asp:TextBox id="txtLastName" Runat="server" /> </div> </form> </body> </html>
When you provide a Label
control with an AssociatedControlID
property, the Label
control is rendered as an HTML <label>
tag instead of an HTML <span>
tag. For example, if you select View Source on your web browser, you’ll see that the first Label
in Listing 2.3 renders the following content to the browser:
<label for="txtFirstName" id="lblFirstName">First Name:</label>
Always use a Label
control with an AssociatedControlID
property when labeling form fields. This is important when you need to make your website accessible to persons with disabilities. If someone is using an assistive device, such as a screen reader, to interact with your website, the AssociatedControlID
property enables the assistive device to associate the correct label with the correct form field.
A side benefit of using the AssociatedControlID
property is that clicking a label when this property is set automatically changes the form focus to the associated form input field.
Both the WCAG 1.0 and Section 508 accessibility guidelines require you to use the <label for>
tag when labeling form fields. For more information, see http://www.w3.org/wai and http://www.Section508.gov.
The Literal
control is similar to the Label
control. You can use the Literal
control to display text or HTML content in a browser. However, unlike the Label
control, the Literal
control does not render its content inside of a <span>
tag.
For example, the page in Listing 2.4 uses a Literal
control in the page’s <head>
tag to dynamically modify the title displayed in the browser title bar. The current date is displayed in the Literal
control (see Figure 2.3).
Example 2.4. ShowLiteral.aspx
<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> Sub Page_Load() ltlTitle.Text = DateTime.Now.ToString("D") End Sub </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title><asp:Literal id="ltlTitle" Runat="Server" /></title> </head> <body> <form id="form1" runat="server"> <div> <h1>Look in the title bar</h1> </div> </form> </body> </html>
If you used a Label
control in Listing 2.4 instead of a Literal
control, the uninterpreted <span>
tags would appear in the browser title bar.
The page in Listing 2.4 uses a format specifier to format the date before assigning the date to the Label
control. The D format specifier causes the date to be formatted in a long format. You can use several standard format specifiers with the ToString()
method to format dates, times, currency amounts, and numbers. For a list of these format specifiers, look up the Format Specifiers topic in the index of the Microsoft .NET Framework 2.0 SDK Documentation.
Because the contents of a Literal
control are not contained in a <span>
tag, the Literal
control does not support any of the formatting properties supported by the <span>
tag. For example, the Literal
control does not support either the CssClass
or BackColor
properties.
The Literal
control does support one property that is not supported by the Label
control: the Mode
property. The Mode
property enables you to encode HTML content. The Mode
property accepts any of the following three values:
PassThrough
—. Displays the contents of the control without encoding.
Encode
—. Displays the contents of the control after HTML encoding the content.
Transform
—. Displays the contents of the control after stripping markup that is not supported by the requesting device.
For example, the page in Listing 2.5 contains three Literal
controls that are set to the three possible values of the Mode
property (see Figure 2.4).
Example 2.5. ShowLiteralMode.aspx
<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Show Literal Mode</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Literal id="ltlFirst" Mode="PassThrough" Text="<hr />" Runat="server" /> <br /><br /> <asp:Literal id="ltlSecond" Mode="Encode" Text="<hr />" Runat="server" /> <br /><br /> <asp:Literal id="ltlThird" Mode="Transform" Text="<hr />" Runat="server" /> </div> </form> </body> </html>
When you request the page in Listing 2.5 with a web browser, the first Literal
control displays a horizontal rule, the second Literal
control displays the uninterpreted <hr />
tag, and the final Literal
control displays another horizontal rule. If you requested the page from a device (such as a WML cell phone) that does not support the <hr>
tag, the third <hr />
tag would be stripped.
The ASP.NET Framework includes several controls that you can use to gather user input. In this section, you learn how to use the TextBox
, CheckBox
, and RadioButton
controls. These controls correspond to the standard types of HTML input tags.
The TextBox
control can be used to display three different types of input fields depending on the value of its TextMode
property. The TextMode
property accepts the following three values:
SingleLine
—. Displays a single-line input field.
MultiLine
—. Displays a multi-line input field.
Password
—. Displays a single-line input field in which the text is hidden.
The page in Listing 2.6 contains three TextBox
controls that illustrate all three of the TextMode
values (see Figure 2.5).
Example 2.6. ShowTextBox.aspx
<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Show TextBox</title> </head> <body> <form id="form1" runat="server"> <div> <asp:TextBox id="txtUserName" TextMode="SingleLine" Runat="server" /> <br /><br /> <asp:TextBox id="txtPassword" TextMode="Password" Runat="server" /> <br /><br /> <asp:TextBox id="txtComments" TextMode="MultiLine" Runat="server" /> </div> </form> </body> </html>
You can use the following properties to control the rendering characteristics of the TextBox
control (this is not a complete list):
AccessKey
—. Enables you to specify a key that navigates to the TextBox
control.
AutoCompleteType
—. Enables you to associate an AutoComplete
class with the TextBox
control.
AutoPostBack
—. Enables you to post the form containing the TextBox
back to the server automatically when the contents of the TextBox
is changed.
Columns
—. Enables you to specify the number of columns to display.
Enabled
—. Enables you to disable the text box.
MaxLength
—. Enables you to specify the maximum length of data that a user can enter in a text box (does not work when TextMode
is set to Multiline
).
ReadOnly
—. Enables you to prevent users from changing the text in a text box.
Rows
—. Enables you to specify the number of rows to display.
TabIndex
—. Enables you to specify the tab order of the text box.
Wrap
—. Enables you to specify whether text word-wraps when the TextMode
is set to Multiline
.
The TextBox control also supports the following method:
Focus
—. Enables you to set the initial form focus to the text box.
And, the TextBox
control supports the following event:
TextChanged
—. Raised on the server when the contents of the text box are changed.
When the AutoPostBack
property has the value True
, the form containing the TextBox
is automatically posted back to the server when the contents of the TextBox
changes. For example, the page in Listing 2.7 contains a simple search form. If you modify the contents of the text box and tab out of the TextBox
control, the form is automatically posted back to the server and the contents of the TextBox
are displayed (see Figure 2.6).
Example 2.7. TextBoxAutoPostBack.aspx
<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> Sub txtSearch_TextChanged(ByVal sender As Object, ByVal e As EventArgs) lblSearchResults.Text = "Search for: " & txtSearch.Text End Sub </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>TextBox AutoPostBack</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label id="lblSearch" Text="Search:" Runat="server" /> <asp:TextBox id="txtSearch" AutoPostBack="true" OnTextChanged="txtSearch_TextChanged" Runat="server" /> <hr /> <asp:Label id="lblSearchResults" Runat="server" /> </div> </form> </body> </html>
In Listing 2.7, the TextBox
control’s TextChanged
event is handled. This event is raised on the server when the contents of the TextBox
have been changed. You can handle this event even when you don’t use the AutoPostBack
property.
You should avoid using the AutoPostBack
property for accessibility reasons. Creating a page that automatically reposts to the server can be very confusing to someone using an assistive device such as a screen reader. If you insist on using the AutoPostBack
property, you should include a value for the ToolTip
property that warns the user that the page will be reloaded.
Notice that the TextBox
control also includes a property that enables you to associate the TextBox
with a particular AutoComplete
class. When AutoComplete
is enabled, the user does not need to re-enter common information—such as a first name, last name, or phone number—in a form field. If the user has not disabled AutoComplete
on his browser, then his browser prompts him to enter the same value that he entered previously for the form field (even if the user entered the value for a form field at a different website).
For example, the page in Listing 2.8 asks for your first name, last name, and phone number. Each TextBox
control is associated with a particular AutoComplete
class. The AutoComplete
class specifies the type of information associated with the form field. After you complete the form once, if you return to the same form in the future, you are prompted to enter the same responses (see Figure 2.7).
Example 2.8. ShowAutoComplete.aspx
<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Show AutoComplete</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label id="lblFirstName" Text="First Name:" AssociatedControlID="txtFirstName" Runat="server" /> <br /> <asp:TextBox id="txtFirstName" AutoCompleteType="FirstName" Runat="server" /> <br /><br /> <asp:Label id="lblLastname" Text="Last Name:" AssociatedControlID="txtLastName" Runat="server" /> <br /> <asp:TextBox id="txtLastName" AutoCompleteType="LastName" Runat="server" /> <br /><br /> <asp:Button id="btnSubmit" Text="Submit" Runat="server" /> </div> </form> </body> </html>
When using Internet Explorer, you can configure AutoComplete
by selecting Tools, Internet Options, Content, and clicking the AutoComplete button. The ASP.NET Framework does not support AutoComplete
for other browsers such as FireFox or Opera.
Finally, the TextBox
control supports the Focus()
method. You can use the Focus()
method to shift the initial form focus to a particular TextBox
control. By default, no form field has focus when a page first opens. If you want to make it easier for users to complete a form, you can set the focus automatically to a particular TextBox
control contained in a form.
For example, the page in Listing 2.9 sets the focus to the first of two form fields.
Example 2.9. TextBoxFocus.aspx
<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> Sub Page_Load() txtFirstName.Focus() End Sub </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>TextBox Focus</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label id="lblFirstName" Text="First Name:" AssociatedControlID="txtFirstName" Runat="server" /> <br /> <asp:TextBox id="txtFirstName" AutoCompleteType="FirstName" Runat="server" /> <br /><br /> <asp:Label id="lblLastname" Text="Last Name:" AssociatedControlID="txtLastName" Runat="server" /> <br /> <asp:TextBox id="txtLastName" AutoCompleteType="LastName" Runat="server" /> <br /><br /> <asp:Button id="btnSubmit" Text="Submit" Runat="server" /> </div> </form> </body> </html>
In Listing 2.9, the Page_Load()
event handler sets the form focus to the txtFirstName TextBox
control.
The CheckBox
control enables you to display, well, a check box. The page in Listing 2.10 illustrates how you can use the CheckBox
control in a newsletter signup form (see Figure 2.8).
Example 2.10. ShowCheckBox.aspx
<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> Sub btnSubmit_Click(ByVal sender As Object, ByVal e As EventArgs) lblResult.Text = chkNewsletter.Checked.ToString() End Sub </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Show CheckBox</title> </head> <body> <form id="form1" runat="server"> <div> <asp:CheckBox id="chkNewsletter" Text="Receive Newsletter?" Runat="server" /> <br /> <asp:Button id="btnSubmit" Text="Submit" OnClick="btnSubmit_Click" Runat="server" /> <hr /> <asp:Label id="lblResult" Runat="server" /> </div> </form> </body> </html>
In Listing 2.10, the Checked
property is used to determine whether the user has checked the check box.
Notice that the CheckBox
includes a Text
property that is used to label the CheckBox
. If you use this property, then the proper (accessibility standards–compliant) HTML <label>
tag is generated for the TextBox
.
The CheckBox
control supports the following properties (this is not a complete list):
AccessKey
—. Enables you to specify a key that navigates to the TextBox
control.
AutoPostBack
—. Enables you to post the form containing the CheckBox back to the server automatically when the CheckBox
is checked or unchecked.
Checked
—. Enables you to get or set whether the CheckBox
is checked.
Enabled
—. Enables you to disable the TextBox
.
TabIndex
—. Enables you to specify the tab order of the check box.
Text
—. Enables you to provide a label for the check box.
TextAlign
—. Enables you to align the label for the check box. Possible values are Left and Right.
The CheckBox
control also supports the following method:
Focus
—. Enables you to set the initial form focus to the check box.
And, the CheckBox
control supports the following event:
CheckedChanged
—. Raised on the server when the check box is checked or unchecked.
Notice that the CheckBox
control, like the TextBox
control, supports the AutoPostBack
property. The page in Listing 2.11 illustrates how you can use the AutoPostBack
property to post the form containing the check box back to the server automatically when the check box is checked or unchecked.
Example 2.11. CheckBoxAutoPostBack.aspx
<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> Sub chkNewsletter_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs) lblResult.Text = chkNewsletter.Checked.ToString() End Sub </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>CheckBox AutoPostBack</title> </head> <body> <form id="form1" runat="server"> <div> <asp:CheckBox id="chkNewsletter" Text="Receive Newsletter?" AutoPostBack="true" OnCheckedChanged="chkNewsletter_CheckedChanged" Runat="server" /> <hr /> <asp:Label id="lblResult" Runat="server" /> </div> </form> </body> </html>
The ASP.NET Framework also includes the CheckBoxList
control that enables you to display a list of check boxes automatically. This control is discussed in detail in Chapter 10, “Using List Controls.”
You always use the RadioButton
control in a group. Only one radio button in a group of RadioButton
controls can be checked at a time.
For example, the page in Listing 2.12 contains three RadioButton controls (see Figure 2.9).
Example 2.12. ShowRadioButton.aspx
<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> Sub btnSubmit_Click(ByVal sender As Object, ByVal e As EventArgs) If rdlMagazine.Checked Then lblResult.Text = rdlMagazine.Text End If If rdlTelevision.Checked Then lblResult.Text = rdlTelevision.Text End If If rdlOther.Checked Then lblResult.Text = rdlOther.Text End If End Sub </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Show RadioButton</title> </head> <body> <form id="form1" runat="server"> <div> How did you hear about our Website? <ul> <li> <asp:RadioButton id="rdlMagazine" Text="Magazine Article" GroupName="Source" Runat="server" /> </li> <li> <asp:RadioButton id="rdlTelevision" Text="Television Program" GroupName="Source" Runat="server" /> </li> <li> <asp:RadioButton id="rdlOther" Text="Other Source" GroupName="Source" Runat="server" /> </li> </ul> <asp:Button id="btnSubmit" Text="Submit" Runat="server" OnClick="btnSubmit_Click" /> <hr /> <asp:Label id="lblResult" Runat="server" /> </div> </form> </body> </html>
The RadioButton
controls in Listing 2.12 are grouped together with the RadioButton
control’s GroupName
property. Only one of the three RadioButton
controls can be checked at a time.
The RadioButton
control supports the following properties (this is not a complete list):
AccessKey
—. Enables you to specify a key that navigates to the RadioButton
control.
AutoPostBack
—. Enables you to post the form containing the RadioButton
back to the server automatically when the radio button is checked or unchecked.
Checked
—. Enables you to get or set whether the RadioButton
control is checked.
Enabled
—. Enables you to disable the RadioButton
.
GroupName
—. Enables you to group RadioButton
controls.
TabIndex
—. Enables you to specify the tab order of the RadioButton
control.
Text
—. Enables you to label the RadioButton
control.
TextAlign
—. Enables you to align the RadioButton
label. Possible values are Left
and Right
.
The RadioButton
control supports the following method:
Focus
—. Enables you to set the initial form focus to the RadionButton
control.
Finally, the RadioButton
control supports the following event:
CheckedChanged
—. Raised on the server when the RadioButton
is checked or unchecked.
The page in Listing 2.13 demonstrates how you can use the AutoPostBack
property with a group of RadioButton
controls and detect which RadioButton
control is selected.
Example 2.13. RadioButtonAutoPostBack.aspx
<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> Sub RadioButton_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs) Dim selectedRadioButton As RadioButton = CType(sender, RadioButton) lblResult.Text = selectedRadioButton.Text End Sub </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>RadioButton AutoPostBack</title> </head> <body> <form id="form1" runat="server"> <div> How did you hear about our Website? <ul> <li> <asp:RadioButton id="rdlMagazine" Text="Magazine Article" GroupName="Source" AutoPostBack="true" OnCheckedChanged="RadioButton_CheckedChanged" Runat="server" /> </li> <li> <asp:RadioButton id="rdlTelevision" Text="Television Program" GroupName="Source" AutoPostBack="true" OnCheckedChanged="RadioButton_CheckedChanged" Runat="server" /> </li> <li> <asp:RadioButton id="rdlOther" Text="Other Source" GroupName="Source" AutoPostBack="true" OnCheckedChanged="RadioButton_CheckedChanged" Runat="server" /> </li> </ul> <hr /> <asp:Label id="lblResult" Runat="server" /> </div> </form> </body> </html>
In Listing 2.13, when you select a RadioButton
control, the page is automatically posted back to the server, and the value of the Text
property of the selected RadioButton
control is displayed. Notice that all three of the RadioButton
controls are associated with the same CheckedChanged
event handler. The first parameter passed to the handler represents the particular RadioButton
that was changed.
The ASP.NET Framework also includes the RadioButtonList
control, which enables you to display a list of radio buttons automatically. This control is discussed in detail in Chapter 10, “Using List Controls.”
The ASP.NET Framework includes three controls you can use to submit a form to the server: the Button
, LinkButton
, and ImageButton
controls. These controls have the same function, but each control has a distinct appearance.
In this section, you learn how to use each of these three types of buttons in a page. Next, you learn how to associate client-side scripts with server-side Button
controls. You also learn how to use a button control to post a form to a page other than the current page. Finally, you learn how to handle a button control’s Command event.
The Button
control renders a push button that you can use to submit a form to the server. For example, the page in Listing 2.14 contains a Button
control. When you click the Button
control, the time displayed by a Label
control is updated (see Figure 2.10).
Example 2.14. ShowButton.aspx
<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> Sub btnSubmit_Click(ByVal sender As Object, ByVal e As EventArgs) lblTime.Text = DateTime.Now.ToString("T") End Sub </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Show Button</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Button id="btnSubmit" Text="Submit" OnClick="btnSubmit_Click" Runat="server" /> <br /><br /> <asp:Label id="lblTime" Runat="server" /> </div> </form> </body> </html>
The Button
control supports the following properties (this is not a complete list):
AccessKey
—. Enables you to specify a key that navigates to the Button
control.
CommandArgument
—. Enables you to specify a command argument that is passed to the Command
event.
CommandName
—. Enables you to specify a command name that is passed to the Command
event.
Enabled
—. Enables you to disable the Button
control.
OnClientClick
—. Enables you to specify a client-side script that executes when the button is clicked.
PostBackUrl
—. Enables you to post a form to a particular page.
TabIndex
—. Enables you to specify the tab order of the Button
control.
Text
—. Enables you to label the Button
control.
UseSubmitBehavior
—. Enables you to use JavaScript to post a form.
The Button
control also supports the following method:
Focus
—. Enables you to set the initial form focus to the Button
control.
The Button
control also supports the following two events:
Click
—. Raised when the Button
control is clicked.
Command
—. Raised when the Button control is clicked. The CommandName
and CommandArgument
are passed to this event.
The LinkButton
control, like the Button
control, enables you to post a form to the server. Unlike a Button
control, however, the LinkButton
control renders a link instead of a push button.
The page in Listing 2.15 contains a simple form. The form includes a LinkButton
control that enables you to submit the form to the server and display the contents of the form fields (see Figure 2.11).
Example 2.15. ShowLinkButton.aspx
<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> Sub lnkSubmit_Click(ByVal sender As Object, ByVal e As EventArgs) lblResults.Text = "First Name: " & txtFirstName.Text lblResults.Text &= "<br />Last Name: " & txtLastName.Text End Sub </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Show LinkButton</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label id="lblFirstName" Text="First Name:" AssociatedControlID="txtFirstName" Runat="server" /> <br /> <asp:TextBox id="txtFirstName" Runat="server" /> <br /><br /> <asp:Label id="lblLastName" Text="Last Name:" AssociatedControlID="txtLastName" Runat="server" /> <br /> <asp:TextBox id="txtLastName" Runat="server" /> <br /><br /> <asp:LinkButton id="lnkSubmit" Text="Submit" OnClick="lnkSubmit_Click" Runat="server" /> <br /><br /> <asp:Label id="lblResults" Runat="server" /> </div> </form> </body> </html>
Behind the scenes, the LinkButton
control uses JavaScript to post the form back to the server. The hyperlink rendered by the LinkButton
control looks like this:
<a id="lnkSubmit" href="javascript:__doPostBack('lnkSubmit','')">Submit</a>
Clicking the LinkButton
invokes the JavaScript __doPostBack()
method, which posts the form to the server. When the form is posted, the values of all the other form fields in the page are also posted to the server.
The LinkButton
control supports the following properties (this is not a complete list):
AccessKey
—. Enables you to specify a key that navigates to the Button
control.
CommandArgument
—. Enables you to specify a command argument that is passed to the Command
event.
CommandName
—. Enables you to specify a command name that is passed to the Command
event.
Enabled
—. Enables you to disable the LinkButton
control.
OnClientClick
—. Enables you to specify a client-side script that executes when the LinkButton
is clicked.
PostBackUrl
—. Enables you to post a form to a particular page.
TabIndex
—. Enables you to specify the tab order of the LinkButton
control.
Text
—. Enables you to label the LinkButton
control.
The LinkButton
control also supports the following method:
Focus
—. Enables you to set the initial form focus to the LinkButton
control.
The LinkButton
control also supports the following two events:
Click
—. Raised when the LinkButton
control is clicked.
Command
—. Raised when the LinkButton
control is clicked. The CommandName
and CommandArgument
are passed to this event.
The ImageButton
control, like the Button
and LinkButton
controls, enables you to post a form to the server. However, the ImageButton
control always displays an image.
The page in Listing 2.16 contains an ImageButton
control that posts a simple form back to the server (see Figure 2.12).
Example 2.16. ShowImageButton.aspx
<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> Sub btnSubmit_Click(ByVal sender As Object, ByVal e As ImageClickEventArgs) lblResults.Text = "First Name: " & txtFirstName.Text lblResults.Text &= "<br />Last Name: " & txtLastName.Text End Sub </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Show ImageButton</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label id="lblFirstName" Text="First Name:" AssociatedControlID="txtFirstName" Runat="server" /> <br /> <asp:TextBox id="txtFirstName" Runat="server" /> <br /><br /> <asp:Label id="lblLastName" Text="Last Name:" AssociatedControlID="txtLastName" Runat="server" /> <br /> <asp:TextBox id="txtLastName" Runat="server" /> <br /><br /> <asp:ImageButton id="btnSubmit" ImageUrl="Submit.gif" AlternateText="Submit Form" Runat="server" OnClick="btnSubmit_Click" /> <br /><br /> <asp:Label id="lblResults" Runat="server" /> </div> </form> </body> </html>
The ImageButton
in Listing 2.16 includes both an ImageUrl
and AlternateText
property. The ImageUrl
contains the path to the image that the ImageButton
displays. The AlternateText
property is used to provide alternate text for the image used by screen readers and text-only browsers.
Always include alternate text for any image. The accessibility guidelines require it. Furthermore, remember that some people turn off images in their browsers for a faster surfing experience.
Notice that the event handler for an Image
control’s Click
event is different than that for the other button controls. The second parameter passed to the event handler is an instance of the ImageClickEventArgs
class. This class has the following properties:
X
—. The x coordinate relative to the image the user clicked.
Y
—. The y coordinate relative to the image the user clicked.
You can use the ImageButton
control to create a simple image map. For example, the page in Listing 2.17 contains an ImageButton
that displays an image of a target. If you click the center of the target, then a success message is displayed (see Figure 2.13).
Example 2.17. ImageButtonTarget.aspx
<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> Sub btnTarget_Click(ByVal sender As Object, ByVal e As ImageClickEventArgs) If (e.X > 90 And e.X < 110) And (e.Y > 90 And e.Y < 110) Then lblResult.Text = "You hit the target!" Else lblResult.Text = "You missed!" End If End Sub </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>ImageButton Target</title> </head> <body> <form id="form1" runat="server"> <div> <asp:ImageButton id="btnTarget" ImageUrl="Target.gif" Runat="server" OnClick="btnTarget_Click" /> <br /><br /> <asp:Label id="lblResult" Runat="server" /> </div> </form> </body> </html>
The ImageButton
can be used to create a server-side image map. Server-side image maps are not accessible to persons with disabilities. A better method for creating an ImageMap
is to use the ImageMap
control, which enables you to create a client-side image map. The ImageMap
control is discussed in the next section of this chapter.
The ImageButton
control supports the following properties (this is not a complete list):
AccessKey
—. Enables you to specify a key that navigates to the ImageButton
control.
AlternateText
—. Enables you to provide alternate text for the image (required for accessibility).
DescriptionUrl
—. Enables you to provide a link to a page that contains a detailed description of the image (required to make a complex image accessible).
CommandArgument
—. Enables you to specify a command argument that is passed to the Command
event.
CommandName
—. Enables you to specify a command name that is passed to the Command
event.
Enabled
—. Enables you to disable the ImageButton
control.
GenerateEmptyAlternateText
—. Enables you to set the AlternateText
property to an empty string.
ImageAlign
—. Enables you to align the image relative to other HTML elements in the page. Possible values are AbsBottom
, AbsMiddle
, Baseline
, Bottom
, Left
, Middle
, NotSet
, Right
, TextTop
, and Top
.
ImageUrl
—. Enables you to specify the URL to the image.
OnClientClick
—. Enables you to specify a client-side script that executes when the ImageButton
is clicked.
PostBackUrl
—. Enables you to post a form to a particular page.
TabIndex
—. Enables you to specify the tab order of the ImageButton
control.
The ImageButton
control also supports the following method:
Focus
—. Enables you to set the initial form focus to the ImageButton
control.
The ImageButton
control also supports the following two events:
Click
—. Raised when the ImageButton
control is clicked.
Command
—. Raised when the ImageButton
control is clicked. The CommandName
and CommandArgument
are passed to this event.
All three Button
controls support an OnClientClick
property. You can use this property to execute any client-side code that you need when a button is clicked. The page in Listing 2.18 illustrates how you can use the OnClientClick
property to display a confirmation dialog box (see Figure 2.14).
Example 2.18. ButtonOnClientClick.aspx
<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> Sub btnDelete_Click(sender AS Object, e As EventArgs) lblResult.Text = "All pages deleted!" End Sub </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Button OnClientClick</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Button id="btnDelete" Text="Delete Website" OnClick="btnDelete_Click" OnClientClick="return confirm('Are you sure?')," Runat="server" /> <br /><br /> <asp:Label id="lblResult" Runat="server" /> </div> </form> </body> </html>
In Listing 2.18, the Button
control includes an OnClientClick
property, which executes a JavaScript script when you click the button on the client. The script displays a confirmation dialog box. If the confirmation box returns False
, then the button click is canceled and the form containing the button is not posted to the server.
Because the button controls, like most ASP.NET controls, support expando attributes, you can handle other client-side events simply by adding an arbitrary attribute to the control. If the ASP.NET Framework does not recognize an attribute declared on a button control, the framework simply passes the attribute to the browser.
For example, the page in Listing 2.19 contains a button control that includes onmouseover
and onmouseout
attributes. When you hover your mouse over the button, the text displayed in the button is changed.
Example 2.19. ButtonExpando.aspx
<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Button Expando</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Button id="btnSubmit" Text="Submit" onmouseover="this.value='Click Here!'" onmouseout="this.value='Submit'" Runat="server" /> </div> </form> </body> </html>
By default, if you click a button control, the page containing the control is posted back to itself and the same page is reloaded. However, you can use the PostBackUrl
property to post form data to another page.
For example, the page in Listing 2.20 includes a search form. The Button
control in the page posts the form to another page named ButtonSearchResults.aspx
. The ButtonSearchResults.aspx
page is contained in Listing 2.21.
Example 2.20. ButtonSearch.aspx
<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Button Search</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label id="lblSearch" Text="Search:" Runat="server" /> <asp:TextBox id="txtSearch" Runat="server" /> <asp:Button id="btnSearch" Text="Go!" PostBackUrl="ButtonSearchResults.aspx" Runat="server" /> </div> </form> </body> </html>
Example 2.21. ButtonSearchResults.aspx
<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> Sub Page_Load() If Not IsNothing(PreviousPage) Then Dim txtSearch As TextBox = CType(PreviousPage.FindControl("txtSearch"), TextBox) lblSearch.Text = String.Format("Search For: {0}", txtSearch.Text) End If End Sub </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Button Search Results</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label id="lblSearch" Runat="server" /> </div> </form> </body> </html>
In the Page_Load
event handler in Listing 2.21, the PreviousPage
property is used to get a reference to the previous page (the ButtonSearch.aspx
page in Listing 2.20). Next, the FindControl()
method is used to retrieve the txtSearch TextBox
control from the previous page. Finally, the value entered into the TextBox
is displayed in a label on the page.
As an alternative to using the FindControl()
method to retrieve a particular control from the previous page, you can expose the control through a page property. The page in Listing 2.22 exposes the txtSearch TextBox
through a property named SearchString
. The page posts the form data to a page named ButtonSearchResultsTyped.aspx
, contained in Listing 2.23.
Example 2.22. ButtonSearchTyped.aspx
<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> Public ReadOnly Property SearchString() As String Get Return txtSearch.Text End Get End Property </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Button Search Typed</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label id="lblSearch" Text="Search:" Runat="server" /> <asp:TextBox id="txtSearch" Runat="server" /> <asp:Button id="btnSearch" Text="Go!" PostBackUrl="ButtonSearchResultsTyped.aspx" Runat="server" /> </div> </form> </body> </html>
Example 2.23. ButtonSearchResultsTyped.aspx
<%@ Page Language="VB" %> <%@ PreviousPageType VirtualPath="~/ButtonSearchTyped.aspx" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> Sub Page_Load() If Not IsNothing(Page.PreviousPage) Then lblSearch.Text = String.Format("Search For: {0}", PreviousPage.SearchString) End If End Sub </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Button Search Results Typed</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label id="lblSearch" Runat="server" /> </div> </form> </body> </html>
Notice that the page in Listing 2.23 includes a <%@ PreviousPageType %>
directive. This directive casts the value returned by the PreviousPage
property as an instance of the ButtonSearchTyped
class. Without this directive, the PreviousPage
property would return the previous page as an instance of the generic Page
class.
You can use either method when performing cross-page posts. The first method provides you with an untyped method of retrieving values from the previous page, and the second method provides you with a typed method.
You can specify a default button for a form by using the DefaultButton
property of the server-side Form
control. If you specify a default button, then pressing the keyboard Enter key invokes the button.
For example, the page in Listing 2.24 contains a simple search form. The <form>
tag sets the btnSearch Button
control as the default button on the page.
Example 2.24. ButtonDefaultButton.aspx
<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> Sub btnSearch_Click(ByVal sender As Object, ByVal e As EventArgs) lblResult.Text = "Search for: " & txtSearch.Text End Sub </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Button Default Button</title> </head> <body> <form id="form1" defaultbutton="btnSearch" runat="server"> <div> <asp:Label id="lblSearch" Text="Search:" AssociatedControlID="txtSearch" Runat="server" /> <asp:TextBox id="txtSearch" Runat="server" /> <asp:Button id="btnSearch" Text="Search" OnClick="btnSearch_Click" Runat="server" /> <asp:Button id="btnCancel" Text="Cancel" Runat="server" /> <hr /> <asp:Label id="lblResult" Runat="server" /> </div> </form> </body> </html>
If you open the page in Listing 2.24, type a search phrase, and hit the keyboard Enter key, the form is submitted to the server. Pressing the Enter key causes the btnSearch_Click
event handler to execute because the btnSearch
button is the default button on the page.
All three Button
controls support both the Click
event and the Command
event. The difference between these events is that you can pass a command name and command argument to a Command
event handler but not to a Click
event handler.
For example, the page in Listing 2.25 contains two Button
controls and a BulletedList
control. When you click the first button, the items displayed by the BulletedList
control are sorted in ascending order, and when you click the second button, the items displayed by the BulletedList
control are sorted in descending order (see Figure 2.15).
Example 2.25. ButtonCommand.aspx
<%@ Page Language="VB" %> <%@ Import Namespace="System.Collections.Generic" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> Private groceries As New List(Of String)() Sub Page_Load() groceries.Add("Milk") groceries.Add("Steak") groceries.Add("Fish") End Sub Sub Sort_Command(ByVal sender As Object, ByVal e As CommandEventArgs) If e.CommandName = "Sort" Then Select Case e.CommandArgument.ToString() Case "ASC" groceries.Sort(AddressOf SortASC) Case "DESC" groceries.Sort(AddressOf SortDESC) End Select End If End Sub Sub Page_PreRender() bltGroceries.DataSource = groceries bltGroceries.DataBind() End Sub Function SortASC(ByVal x As String, ByVal y As String) As Integer Return String.Compare(x, y) End Function Function SortDESC(ByVal x As String, ByVal y As String) As Integer Return String.Compare(x, y) * -1 End Function </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Button Command</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Button id="btnSortAsc" Text="Sort ASC" CommandName="Sort" CommandArgument="ASC" OnCommand="Sort_Command" Runat="server" /> <asp:Button id="btnSortDESC" Text="Sort DESC" CommandName="Sort" CommandArgument="DESC" OnCommand="Sort_Command" Runat="server" /> <br /><br /> <asp:BulletedList id="bltGroceries" Runat="server" /> </div> </form> </body> </html>
Both Button
controls include CommandName
and CommandArgument
properties. Furthermore, both Button
controls are wired to the same Sort_Command()
event handler. This event handler checks the CommandName
and CommandArgument
properties when determining how the elements in the BulletedList
should be sorted.
The ASP.NET framework includes two controls for displaying images: the Image
and ImageMap
controls. The Image
control simply displays an image. The ImageMap
control enables you to create a client-side, clickable, image map.
The page in Listing 2.26 randomly displays one of three images. The image is displayed by setting the ImageUrl
property of the Image
control contained in the body of the page.
Example 2.26. ShowImage.aspx
<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> Sub Page_Load() Dim rnd As New Random() Select Case rnd.Next(3) Case 0 imgRandom.ImageUrl = "Picture1.gif" imgRandom.AlternateText = "Picture 1" Case 1 imgRandom.ImageUrl = "Picture2.gif" imgRandom.AlternateText = "Picture 2" Case 2 imgRandom.ImageUrl = "Picture3.gif" imgRandom.AlternateText = "Picture 3" End Select End Sub </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Show Image</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Image id="imgRandom" Runat="server" /> </div> </form> </body> </html>
The Image
control supports the following properties (this is not a complete list):
AlternateText
—. Enables you to provide alternate text for the image (required for accessibility).
DescriptionUrl
—. Enables you to provide a link to a page that contains a detailed description of the image (required to make a complex image accessible).
GenerateEmptyAlternateText
—. Enables you to set the AlternateText
property to an empty string.
ImageAlign
—. Enables you to align the image relative to other HTML elements in the page. Possible values are AbsBottom
, AbsMiddle
, Baseline
, Bottom
, Left
, Middle
, NotSet
, Right
, TextTop
, and Top
.
ImageUrl
—. Enables you to specify the URL to the image.
The Image
control supports three methods for supplying alternate text. If an image represents page content, then you should supply a value for the AlternateText
property. For example, if you have an image for your company’s logo, then you should assign the text "My Company Logo" to the AlternateText
property.
If an Image
control represents something really complex—such as a bar chart, pie graph, or company organizational chart—then you should supply a value for the DescriptionUrl
property. The DescriptionUrl
property links to a page that contains a long textual description of the image.
Finally, if the image is used purely for decoration (it expresses no content), then you should set the GenerateEmptyAlternateText
property to the value True
. When this property has the value True
, then an alt="" attribute
is included in the rendered <img>
tag. Screen readers know to ignore images with empty alt
attributes.
The ImageMap
control enables you to create a client-side image map. An image map displays an image. When you click different areas of the image, things happen.
For example, you can use an image map as a fancy navigation bar. In that case, clicking different areas of the image map navigates to different pages in your website.
You also can use an image map as an input mechanism. For example, you can click different product images to add a particular product to a shopping cart.
An ImageMap
control is composed out of instances of the HotSpot
class. A HotSpot
defines the clickable regions in an image map. The ASP.NET framework ships with three HotSpot
classes:
CircleHotSpot
—. Enables you to define a circular region in an image map.
PolygonHotSpot
—. Enables you to define an irregularly shaped region in an image map.
RectangleHotSpot
—. Enables you to define a rectangular region in an image map.
The page in Listing 2.27 contains a navigation bar created with an ImageMap
control. The ImageMap
contains three RectangleHotSpots
that delimit the three buttons displayed by the navigation bar (see Figure 2.16).
Example 2.27. ImageMapNavigate.aspx
<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>ImageMap Navigate</title> </head> <body> <form id="form1" runat="server"> <div> <asp:ImageMap id="mapNavigate" ImageUrl="ImageBar.jpg" Runat="server"> <asp:RectangleHotSpot NavigateUrl="Home.aspx" Left="0" Top="0" Right="100" Bottom="50" AlternateText="Navigate to Home" /> <asp:RectangleHotSpot NavigateUrl="Products.aspx" Left="100" Top="0" Right="200" Bottom="50" AlternateText="Navigate to Products" /> <asp:RectangleHotSpot NavigateUrl="Services.aspx" Left="200" Top="0" Right="300" Bottom="50" AlternateText="Navigate to Services" /> </asp:ImageMap> </div> </form> </body> </html>
Each RectangleHotSpot
includes Left
, Top
, Right
, and Bottom
properties that describe the area of the rectangle. Each RectangleHotSpot
also includes a NavigateUrl
property that contains the URL to which the region of the image map links.
Rather than use an image map to link to different pages, you can use it to post back to the same page. For example, the page in Listing 2.28 uses an ImageMap
control to display a menu. When you click different menu items represented by different regions of the image map, the text contained in the TextBox
control is changed (see Figure 2.17).
Example 2.28. ImageMapPostBack.aspx
<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> Sub mapMenu_Click(ByVal sender As Object, ByVal e As ImageMapEventArgs) Select Case e.PostBackValue Case "ToUpper" txtText.Text = txtText.Text.ToUpper() Case "ToLower" txtText.Text = txtText.Text.ToLower() Case "Erase" txtText.Text = String.Empty End Select End Sub </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>ImageMap PostBack</title> </head> <body> <form id="form1" runat="server"> <div> <asp:ImageMap id="mapMenu" ImageUrl="MenuBar.gif" HotSpotMode="PostBack" Runat="server" OnClick="mapMenu_Click"> <asp:RectangleHotSpot PostBackValue="ToUpper" Left="0" Top="0" Right="100" Bottom="30" AlternateText="To Uppercase" /> <asp:RectangleHotSpot PostBackValue="ToLower" Left="100" Top="0" Right="200" Bottom="30" AlternateText="To Uppercase" /> <asp:RectangleHotSpot PostBackValue="Erase" Left="200" Top="0" Right="300" Bottom="30" AlternateText="To Uppercase" /> </asp:ImageMap> <br /> <asp:TextBox id="txtText" TextMode="MultiLine" Columns="40" Rows="5" Runat="server" /> </div> </form> </body> </html>
Notice that the ImageMap
control has its HotSpotMode
property set to the value PostBack
. Also, the ImageMap
is wired to a Click
event handler named mapMenu_Click
.
Each HotSpot
contained in the ImageMap
control has a PostBackValue
property. The mapMenu_Click
handler reads the PostBackValue
from the region clicked and modifies the text displayed by the TextBox
control.
The ImageMap
control supports the following properties (this is not a complete list):
AccessKey
—. Enables you to specify a key that navigates to the ImageMap
control.
AlternateText
—. Enables you to provide alternate text for the image (required for accessibility).
DescriptionUrl
—. Enables you to provide a link to a page which contains a detailed description of the image (required to make a complex image accessible).
GenerateEmptyAlternateText
—. Enables you to set the AlternateText
property to an empty string.
HotSpotMode
—. Enables you to specify the behavior of the image map when you click a region. Possible values are Inactive
, Navigate
, NotSet
, and PostBack
.
HotSpots
—. Enables you to retrieve the collection of HotSpots
contained in the ImageMap
control.
ImageAlign
—. Enables you to align the image map with other HTML elements in the page. Possible values are AbsBottom
, AbsMiddle
, Baseline
, Bottom
, Left
, Middle
, NotSet
, Right
, TextTop
, and Top
.
ImageUrl
—. Enables you to specify the URL to the image.
TabIndex
—. Enables you to specify the tab order of the ImageMap
control.
Target
—. Enables you to open a page in a new window.
The ImageMap
control also supports the following method:
Focus
—. Enables you to set the initial form focus to the ImageMap
control.
Finally, the ImageMap
control supports the following event:
Click
—. Raised when you click a region of the ImageMap
and the HotSpotMode
property is set to the value PostBack
.
The Panel
control enables you to work with a group of ASP.NET controls.
For example, you can use a Panel
control to hide or show a group of ASP.NET controls. The page in Listing 2.29 contains a list of RadioButton
controls which can be used to select your favorite programming language. The last RadioButton
is labeled Other
. If you select the Other
radio button, the contents of a Panel
control are revealed (see Figure 2.18).
Example 2.29. ShowPanel.aspx
<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> Sub btnSubmit_Click(ByVal sender As Object, ByVal e As EventArgs) If rdlOther.Checked Then pnlOther.Visible = True Else pnlOther.Visible = False End If End Sub </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Show Panel</title> </head> <body> <form id="form1" runat="server"> <div> Select your favorite programming language: <br /><br /> <asp:RadioButton id="rdlVisualBasic" GroupName="language" Text="Visual Basic" Runat="server" /> <br /><br /> <asp:RadioButton id="rdlCSharp" GroupName="language" Text="C#" Runat="server" /> <br /><br /> <asp:RadioButton id="rdlOther" GroupName="language" Text="Other Language" Runat="server" /> <br /> <asp:Panel id="pnlOther" Visible="false" Runat="server"> <asp:Label id="lblOther" Text="Other Language:" AssociatedControlID="txtOther" Runat="server" /> <asp:TextBox id="txtOther" Runat="server" /> </asp:Panel> <br /><br /> <asp:Button id="btnSubmit" Text="Submit" OnClick="btnSubmit_Click" Runat="server" /> </div> </form> </body> </html>
Notice that the Panel
control is declared with a Visible
property that has the value False
. Because the Visible
property is set to the value False
, the Panel
control and any controls contained in the Panel
control are not rendered when the page is requested.
If you select the RadioButton
control labeled Other
, then the Visible
property is set to the value True
and the contents of the Panel
control are displayed.
Every control in the ASP.NET framework supports the Visible
property. When Visible
is set to the value False
, the control does not render its contents.
The Panel
control supports the following properties (this is not a complete list):
DefaultButton
—. Enables you to specify the default button in a Panel
. The default button is invoked when you press the Enter button.
Direction
—. Enables you to get or set the direction in which controls that display text are rendered. Possible values are NotSet
, LeftToRight
, and RightToLeft
.
GroupingText
—. Enables you to render the Panel
control as a fieldset with a particular legend.
HorizontalAlign
—. Enables you to specify the horizontal alignment of the contents of the Panel. Possible values are Center
, Justify
, Left
, NotSet
, and Right
.
ScrollBars
—. Enables you to display scrollbars around the panel’s contents. Possible values are Auto
, Both
, Horizontal
, None
, and Vertical
.
By default, a Panel
control renders a <div>
tag around its contents. If you set the GroupingText
property, however, the Panel
control renders a <fieldset>
tag. The value that you assign to the GroupingText
property appears in the <fieldset>
tag’s <legend>
tag. Listing 2.30 demonstrates how you can use the GroupingText
property (see Figure 2.19).
Example 2.30. PanelGroupingText.aspx
<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Panel Grouping Text</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Panel id="pnlContact" GroupingText="Contact Information" Runat="server"> <asp:Label id="lblFirstName" Text="First Name:" AssociatedControlID="txtFirstName" Runat="server" /> <br /> <asp:TextBox id="txtFirstName" AutoCompleteType="FirstName" Runat="server" /> <br /><br /> <asp:Label id="lblLastname" Text="Last Name:" AssociatedControlID="txtLastName" Runat="server" /> <br /> <asp:TextBox id="txtLastName" AutoCompleteType="LastName" Runat="server" /> <br /><br /> <asp:Button id="btnSubmit" Text="Submit" Runat="server" /> </asp:Panel> </div> </form> </body> </html>
According to the accessibility guidelines, you should use <fieldset>
tags when grouping related form fields in long forms.
The ScrollBars
property enables you to display scrollbars around a panel’s contents. For example, the page in Listing 2.31 contains a Panel
control that contains a BulletedList
control that displays 100 items. The panel is configured to scroll when its contents overflow its width or height (see Figure 2.20).
Example 2.31. PanelScrollBars.aspx
<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> Sub Page_Load() For i As Integer = 1 To 100 bltList.Items.Add("Item " & i.ToString()) Next End Sub </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <style type="text/css"> html { background-color:silver; } .contents { background-color:white; width:200px; height:200px; } </style> <title>Panel ScrollBars</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Panel id="pnlContent" ScrollBars="Auto" CssClass="contents" Runat="server"> <asp:BulletedList id="bltList" Runat="server" /> </asp:Panel> </div> </form> </body> </html>
Don’t use the values Horizontal
or Vertical
with the ScrollBars
property when you want the scrollbars to appear in browsers other than Microsoft Internet Explorer. If you want the scrollbars to appear in FireFox
and Opera
, use either the value Auto
or Both
.
When enabling scrollbars with the Panel
control, you must specify a particular width and height to display the scrollbars. In Listing 2.31, the width and height are specified in a Cascading Style Sheet class. Alternatively, you can specify the width and height with the Panel
control’s Width
and Height
properties.
The HyperLink
control enables you to create a link to a page. Unlike the LinkButton
control, the HyperLink
control does not submit a form to a server.
For example, the page in Listing 2.32 displays a hyperlink that randomly links to a page in your application.
Example 2.32. ShowHyperLink.aspx
<%@ Page Language="VB" %> <%@ Import Namespace="System.IO" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> Sub Page_Load() lnkRandom.NavigateUrl = GetRandomFile() End Sub Function GetRandomFile() As String Dim files As String() = Directory.GetFiles(MapPath(Request.ApplicationPath), "*.aspx") Dim rnd As New Random() Dim rndFile As String = files(rnd.Next(files.Length)) Return Path.GetFileName(rndFile) End Function </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Show HyperLink</title> </head> <body> <form id="form1" runat="server"> <div> <asp:HyperLink id="lnkRandom" Text="Random Link" Runat="server" /> </div> </form> </body> </html>
In the Page_Load
event handler in Listing 2.32, a random file name from the current application is assigned to the NavigateUrl
property of the HyperLink
control.
The HyperLink
control supports the following properties (this is not a complete list):
Enabled
—. Enables you to disable the hyperlink.
ImageUrl
—. Enables you to specify an image for the hyperlink.
NavigateUrl
—. Enables you to specify the URL represented by the hyperlink.
Target
—. Enables you to open a new window.
Text
—. Enables you to label the hyperlink.
Notice that you can specify an image for the HyperLink
control by setting the ImageUrl
property. If you set both the Text
and ImageUrl
properties, then the ImageUrl
property takes precedence.
In this chapter, you were introduced to the core controls of the ASP.NET 2.0 framework. You learned how to display information using the Label
and Literal
controls. You also learned how to accept user input using the TextBox
, CheckBox
, and RadioButton
controls.
In the second part of this chapter, you learned how to use the different button controls—the Button
, LinkButton
, and ImageButton
controls—to submit a form. You learned how to post forms between pages. You also learned how to set a default button.
Finally, we discussed the Panel
and HyperLink
controls. You learned how to hide and display a group of controls with the Panel
control. You also learned how to create dynamic links with the HyperLink
control.