- Overview of Web Form Pages
- Adding Server Controls
- Handling Events
- Summary
Adding Server Controls
Unlike standard HTML pages, Web Form Pages can contain Web server controls. Web server controls represent the user interface elements in a page. Unlike normal HTML tags, server controls have properties, methods, and events that you can access within your code.
There are two types of server controls that you can add to a Web Form PageHTML controls or Web Forms controls.
The HTML controls directly reflect existing HTML tags. For example, there is an HTML control that represents an HTML <form> tag, an HTML control that represents an HTML <table> tag, and so on. You can take an existing HTML document and quickly convert the HTML elements contained in the document into server controls by taking advantage of the HTML controls.
There are more Web controls than HTML controls. The Web controls do not directly reflect existing HTML tags. For example, the DataGrid Web control enables you to display and edit database data and the Calendar control enables you to display an interactive calendar.
In the following sections, you learn how to add both HTML and Web controls to your Web Form Pages.
Using HTML Controls
Within Design View, you can convert any HTML element in a page to an HTML control. To convert an element, right-click the element within Design View and select Run As Server Control. After you convert an HTML element to a server control, it will appear with a green glyph that looks something like a VCR play button (see Figure 3.4).
Figure 3.4 Converting an HTML text field to a server control.
For example, to convert an HTML text field into an HTML control, do the following:
Add a Web Form Page to your project and switch to Design View.
Add a text field to your Web Form Page by double-clicking the Text Field element under the HTML tab on the Toolbox.
Right-click the text field on the Designer surface and select Run As Server Control.
When you added the text field to the Web Form Page in step 2, the following HTML tag was added to the page (you can see this tag by switching to HTML View):
<INPUT type="text">
After you convert the text field to an HTML control, the tag is converted to look like the following:
<INPUT type="text" id=Text1 name=Text1 runat="server">
You should notice that three new attributes are added to the HTML tag: id, name, and runat. The id attribute provides the control with a unique identifier for the page. The name attribute provides the control with a name for the form. Finally, and most importantly, the runat="server" attribute marks the HTML tag as a server control.
When you convert an HTML tag into an HTML control, the tag is automatically converted to one of the following HTML controls:
HtmlAnchor Represents a hyperlink tag
HtmlButton Represents a button tag
HtmlForm Represents a form tag
HtmlGenericControl Represents any HTML tag not explicitly represented by another HTML control
HtmlImage Represents an image tag
HtmlInputButton Represents a submit or reset button
HtmlInputCheckbox Represents a check box tag
HtmlInputFile Represents a file upload button
HtmlInputHidden Represents a hidden form field
HtmlInputImage Represents an image button
HtmlInputRadioButton Represents a radio button
HtmlInputText Represents a text field or password field
HtmlSelect Represents a select tag (a drop-down list or list box)
HtmlTable Represents a table tag
HtmlTableCell Represents a table cell tag
HtmlTableRow Represents a table row tag
HtmlTextArea Represents a text area
If you convert an image into an HTML control, the image tag is converted into an HtmlImage control. If you convert a tag that does not have a corresponding control, the tag is converted into an HtmlGenericControl. For example, if you convert a <span> tag into a control, the control is represented by the HtmlGenericControl control.
Using Web Controls
Unlike HTML controls, Web Forms controls do not directly correspond to existing HTML controls. You can find all of the Web Forms controls under the Web Forms tab on the toolbar.
The Web Forms controls can be divided into three groups. The first group of Web controls represents basic form and page elements:
CheckBox Represents a single check box
CheckBoxList Represents a group of multiple check boxes
DropDownList Represents a drop-down list of items
Hyperlink Represents a hyperlink to a new page
Image Represents an image
ImageButton Represents an image button
Label Represents a label
LinkButton Represents a hyperlink that submits a form to the same page
Listbox Represents a list box of items
Literal Represents static text or HTML in a page
Panel Represents a container other controls
Placeholder Represents a spot on the page where other controls can be added
RadioButton Represents a single radio button
RadioButtonList Represents a group of multiple radio buttons
Table Represents an HTML table
TextBox Represents a single-line, multi-line, or password text box
You'll learn how to use many of the controls in this first group in the following sections of this chapter.
There's also a second group of Web controls that enable you to perform form validation. The following is a list of the controls in this group:
CompareValidator Enables you to validate the data in a form field against a fixed value or other form field
CustomValidator Enables you to validate the data in a form field by using a custom subroutine
RangeValidator Enables you to validate the data in a form field against a minimum and maximum value
RegularExpressionValidator Enables you to validate the data in a form field against a regular expression
RequiredFieldValidator Enables you to validate the data in a form field by checking whether the form field contains a value
ValidationSummary Enables you to display a summary of validation error messages on a page
You'll learn how to validate forms with the validation controls in Chapter 4, "Validating Web Form Pages."
There's a third group of controls that enable you to format, display, and edit data:
Repeater Enables you to format items from a data source
DataList Enables you to format items from a data source in multiple columns and create interactive menus
DataGrid Enables you to format, sort, page through, and edit items from a data source
You'll learn how to take advantage of the data controls in the second part of this book, "Working with Database Data."
Finally, the members of the last group of controls are harder to categorize. The Web controls in this group enable you to perform more specialized tasks:
AdRotator Can be used to randomly display banner advertisements
Calendar Can be used to display an interactive calendar
CrystalReportViewer Can be used to display reports with Crystal Reports
Xml Can be used to display XML documents
Adding Label Controls
There are two types of labels that you can add from the Toolbox. You can add an HTML label from the HTML tab or a Label Web Forms control from the Web Forms tab. It's important to not confuse these two types of labels.
A Web Forms Label control, unlike a standard HTML label, enables you to dynamically assign content to an area of a page. For example, you can use a Label control to display the current time, display the number of records in a database table, or display an error when validating a form.
A Label control has one important propertythe Text property. In your code, you can assign any text to the Text property that you want. For example, earlier in this chapter, in the "Creating a Simple Web Form Page" section, you assigned a random fortune to a Label control with a line of code that looks like the following:
C#
Label1.Text = colFortunes[ objRan.Next( 3 ) ].ToString();
VB.NET
Label1.Text = colFortunes(objRan.Next(3))
One potentially confusing thing about a Web Forms Label control is that you cannot assign text to it in the same way as you can assign text to an HTML label. If you want to assign text to an HTML label, you can simply double-click the label and type the text. When using a Web Forms Label control, on the other hand, you need to explicitly set the value of the Text property.
For example, suppose that you want to add a Label control to a page that, by default, displays the text "Hello World!". To do so, perform the following steps:
Double-click the Label control under the Web Forms tab to add a Label control to a page.
Select the label from the drop-down list in the Properties window.
Find the Text property in the Properties window and enter the value "Hello World!".
After you complete these steps, the label should display the text "Hello World!".
Adding Button Controls
There are three types of button controls that you can add to a Web Form Page:
Button Displays the normal form submit pushbutton
ImageButton Displays an image for the button
LinkButton Displays a hypertext link for a button
All three types of buttons submit a form and any information it contains back to the Web server. The buttons differ only in their appearance.
For example, suppose that you want to create a page that displays the current time. However, you want to add a button to the page that enables you to refresh the current time whenever it is clicked.
First, you need to add the necessary controls to the Designer surface:
Select Add Web Form from the Project menu. Enter the name RefreshTime.aspx for the page and click Open.
Add a Web Forms Label control to the page by dragging the Label control from under the Web Forms tab on the toolbar onto the Designer surface.
Add a Button control to the page by dragging the Button control from under the Web Forms tab on the toolbar onto the Designer surface.
Next, you need to add code to the Code Editor that executes whenever you click the button:
-
Double-click the Button control on the Designer surface. Double-clicking the button should switch you to the Code Editor and the cursor should automatically appear within a method named Button1_Click().
- Within the Button1_Click() method, enter the following line of
code:
C#
Label1.Text = DateTime.Now.ToString();
VB.NET
Label1.Text = DateTime.Now
-
Right-click the Web Form Page in the Solution Explorer window and select Build and Browse.
When you have completed these steps, a page similar to the one in Figure 3.5 should be displayed.
Figure 3.5 Adding a Button control to a Web Form Page.
Adding TextBox Controls
A TextBox Web control represents an HTML text field. However, unlike a standard HTML text field, a TextBox control has properties, methods, and events that you can manipulate in your code.
The most important property of a text box is the Text property. You can use the Text property to assign a default value to a text box in your code. You can also use the Text property to read a value that a user has entered into the text box.
For example, suppse that you want to create a Web Form Page with Label, TextBox, and Button controls. When someone enters text into the text box and clicks the button, the text is copied from the TextBox control to the Label control.
Perform the following steps to add the necessary controls:
Create a new Web Form Page named CopyField.aspx by selecting Add Web Form from the Project menu.
Add a Label control to the page by double-clicking the Label control under the Web Forms tab on the toolbar.
Add a TextBox control to the page by double-clicking the TextBox control under the Web Forms tab on the toolbar.
Add a Button control to the page by double-clicking the Button control under the Web Forms tab on the toolbar.
Next, you need to add the code that executes when you click the Button control:
-
Double-click the Button control on the Designer surface. Double-clicking the button should switch you to the Code Editor and the cursor should automatically appear within a method named Button1_Click().
- Within the Button1_Click() method, enter the following line of
code:
C#
Label1.Text = TextBox1.Text;
VB.NET
Label1.Text = TextBox1.Text
-
Right-click the Web Form Page in the Solution Explorer window and select Build and Browse.
If you enter text into the TextBox control and click the button, the text should be copied to the Label control (see Figure 3.6).
Figure 3.6 Copying the value of a TextBox control to a Label control.
A TextBox control can represent a single-line, multi-line, or a password field. To display different types of fields with a TextBox control, you assign different values to the TextBox control's TextMode property. (You can modify the TextMode property in the Properties window.)
By default, the TextMode property has the value SingleLine and a single-line text field is displayed. You specify the width of a single-line text box by assigning a value to the control's Columns property. You can indicate a maximum length for a single-line text box with the MaxLength property. (The maximum length is specified in characters.)
If you assign the value Password to the TextMode property, the text box displays a password field. A password text box works in exactly the same way as a single-line text box except for the fact that any characters entered into the text box are hidden (characters are echoed with asterisks).
Finally, if you assign the value MultiLine to the TextMode property, the text box renders a text area. When creating a multi-line text box, you can assign values to the both the Columns and Rows properties. However, any value assigned to the MaxLength property is ignored.
You can also assign a value to the Wrap property when working with a multi-line text box. When Wrap has the value True, text automatically word wraps within the text box. When Wrap is False, text continues scrolling to the right until you enter a carriage return.
Adding List Controls
You can use any of the following controls to display a list of items:
ListBox
DropDownList
RadioButtonList
CheckBoxList
All of the list controls share common properties because they all derive from the base ListControl class. One of the most important of these properties is the Items property. The Items property represents the individual list items displayed by the control.
Suppose, for example, that you want to display a list of products in a ListBox control. Perform the following steps to do so:
Double-click the ListBox control in the Web Forms tab on the Toolbox.
In the Properties window, click the ellipsis that appears next to the Items property.
-
Click the Add button in the ListItem Collection Editor (see Figure 3.7).
Enter Shaving Cream for the value of the Text property in the ListItem Properties pane of the ListItem Collection Editor.
Click the Add button.
Enter Shampoo for the value of the Text property in the ListItem Properties pane of the ListItem Collection Editor.
Click OK.
Right-click the Web Form Page in the Solution Explorer window and select Build and Browse.
Figure 3.7 The ListItem Collection Editor.
After you complete these steps, the list box will display the two products: Shaving Cream and Shampoo.
All the list controls have a property named SelectedItem that represents the currently selected list item in the list control. You can use SelectedItem.Text to return the Text property of a list item and SelectedItem.Value to return the Value property of a list item. The Text property represents the text that the list control displays, and the Value property represents a hidden value associated with the list item.
Suppose that, after creating a list box that displays a list of products, you want to show the selected item from the list box in a Label control.
Perform the following steps to add the necessary controls:
Create a new Web Form Page named ShowList.aspx by selecting Add Web Form from the Project menu.
Drag the ListBox control from under the Web Forms tab on the Toolbox onto the Designer surface.
Add a couple list items to the ListBox by selecting ListBox in the Properties window and clicking the ellipsis next to the Items property.
Drag the Label control from under the Web Forms tab on the Toolbox onto the Designer surface to add a Label control to your page.
Drag the Button control under the Web Forms tab on the Toolbox onto the Designer surface to add a Button control to your page.
Next, add the code that displays the selected list item:
-
Double-click the Button control on the Designer surface. This will switch you to the Code Editor and the cursor should appear within the Button1_Click() method.
- Enter the following line of code in the Button1_Click() method:
C#
Label1.Text = ListBox1.SelectedItem.Text;
VB.NET
Label1.Text = ListBox1.SelectedItem.Text
-
Right-click the Web Form Page in the Solution Explorer window and select Build and Browse.
If you select an item in the list box and click the button, the text of the selected item will appear in the Label control (see Figure 3.8).
Figure 3.8 Displaying the SelectedItem from a ListBox control.
Using the AutoPostBack Property
Several of the Web controls that represent form elements, such as the list controls and the TextBox control, have a special property called the AutoPostBack property. When AutoPostBack has the value True, any change to the control causes the form that contains the control to be automatically posted back to the server.
CAUTION
The AutoPostBack property uses client-side JavaScript. Older browsers do not support JavaScript, and the AutoPostBack property will fail to function correctly with these browsers.
For example, one common user interface element found in Web applications is a drop-down list used as a navigation menu. When you pick an option in the drop-down list, you are automatically brought to a new page without even clicking a button. Changing the selected item is enough to cause the page to be automatically posted back to the server.
You can create a DropDownList control that automatically posts back to the server by performing the following steps.
First, you need to add the necessary Web Forms controls:
Create a new Web Form Page named AutoPostForm.aspx by selecting Add Web Form from the Project menu.
Drag the DropDownList control from under the Web Forms tab on the Toolbox onto the Designer surface to add a DropDownList control to your page.
In the Properties window, select the DropDownList control and assign the value True to the AutoPostBack property.
In the Properties window open the ListItem Collection Editor dialog box by clicking the ellipsis next to the Items property.
Add a list item with the text Home and the value home.aspx.
Add a list item with the text Products and the value products.aspx.
Click OK to close the ListItem Collection Editor dialog box.
Next, you need to add code that executes whenever a new item is selected in the DropDownList control:
-
Double-click the DropDownList control on the Designer surface. Doing this will switch you to the Code Editor and add a new method named DropDownList1_SelectedIndexChanged().
- Type the following lines of code in the DropDownList1_SelectedIndexChanged()
method:
C#
Response.Redirect(DropDownList1.SelectedItem.Value);
VB.NET
Response.Redirect(DropDownList1.SelectedItem.Value)
-
In the Solution Explorer window, right-click the Web Form Page and select Build and Browse.
If you change the selected item in the DropDownList control to Products, the Products.aspx page will automatically load. (You'll receive a 404 Not Found error if the Products.aspx page has not been added to your project.)
Grouping Controls with Panels
You can group controls together on a page by using the Panel control. The advantage of grouping controls within Panel controls is that you can hide or display the controls as a single group.
The Panel control has a property named Visible. When the Visible property is assigned the value False, all elements contained in the panel are hidden.
For example, suppose that you want to display one or another set of questions in an HTML form, depending on the answer a user enters for a previous form question. You can place the two separate sets of questions in two Panel controls. You can then selectively hide or display the contents of each Panel control by modifying the Panel control's Visible property.
To hide or display the contents of a Panel control when a Button control is clicked, do the following:
First, you need to add the necessary controls to the page:
Create a new Web Form Page named ShowPanel.aspx by selecting Add Web Form from the Project menu.
Add a Panel control to the Web Form Page by dragging the Panel control located under the Web Forms tab on the Toolbox onto the Designer surface.
Click the Panel control twice on the Designer surface and erase the text "Panel."
Stretch the Panel control on the Designer surface by pulling the handles that appear around the control with your mouse.
Add an HTML label to the Panel control by selecting the label element located under the HTML tab on the Toolbox and dragging the element onto the Panel control on the Designer surface.
Click the HTML Label control on the Designer surface and enter the text "Hello World!".
Add a Button control to the Web Form Page by dragging the Button control located under the Web Forms tab on the Toolbox onto the Designer surface.
Next, you need to add the code that hides or displays the contents of the panel:
-
Double-click the Button control on the Designer surface. This will switch you to the Code Editor and add a new method named Button1_Click().
- Enter the following line of code in the Button1_Click() method:
C#
Panel1.Visible = !Panel1.Visible;
VB.NET
Panel1.Visible = Not Panel1.Visible
-
In the Solution Explorer window, right-click the Web Form Page and select Build and Browse.
When you click the button, the text "Hello World!" should disappear. When you click the button again, the text should reappear (see Figure 3.9).
Figure 3.9 Hiding and displaying controls with a Panel control.
NOTE
A Panel control uses flow layout. Consequently, you cannot precisely position elements within a Panel control. You can, however, add a Grid Layout Panel or a Table to a Panel control when you want to have more control over the layout of the elements within a panel.
In this case, we simply added an HTML Label control to a single panel on a page. However, you can use the same technique to add multiple Panel controls to a page that contain multiple elements, such as TextBox and DropDownList controls.
Formatting Web Controls
All the Web controls share a common set of formatting properties (all the Web controls derive from the base WebControl class). You can use these properties to modify such properties as the font and color of the controls. You can modify the following properties in the Properties window for each control:
AccessKey A keyboard shortcut to the control. For example, if you enter the letter A, you can navigate to the control by pressing Alt+A on your keyboard.
BackColor The background color displayed behind the control. Modifying this property opens the Color Dialog box that enables you to pick Custom, Web, or System colors.
BorderColor The color used for the border of the control. Modifying this property opens the Color Dialog box that enables you to pick Custom, Web, or System colors.
BorderStyle The border style used for the control. Possible values include Solid, Dashed, and Groove.
BorderWidth The size of the control's border. This value can be specified in pixels or, in the case of more recent browsers, you can specify other units.
CssClass The Cascading Style Sheet class to associate with the control.
Enabled The state of the control. When Enabled is False, the control appears ghosted on certain browsers such as Microsoft Internet Explorer version 4.0 or later.
Font The font used with the control. You can select the name (typeface) and size of the font and whether the font appears in bold, italic, overline, strikeout, or underline.
ForeColor The foreground color used with the control. Modifying this property opens the Color Dialog box that enables you to pick Custom, Web, or System colors.
Height The height of the control in pixels or, in the case of more recent browsers, you can specify other units.
TabIndex The tab index of the control in a group of controls. Modifies the tab order of controls in a form when used with Internet Explorer 4.0 or later.
ToolTip The pop-up text message displayed above a control when you hover the mouse over it.
Width The width of the control in pixels or, in the case of more recent browsers, you can specify other units.
For example, you can use these properties to create a Panel control with a dashed red border, and a pink background (see Figure 3.10).
Figure 3.10 Using formatting properties.
You should understand that not all of these properties work with all controls. For example, modifying an ImageButton control's Font property is both harmless and meaningless. Furthermore, many of these properties, such as the AccessKey and TabIndex properties, only work with Internet Explorer version 4.0 and later (these properties are ignored on other browsers).
The values of several of these properties, such as the Width and Height properties, are specified in units. The default unit for these properties is the pixel. For example, if you enter 120 for the width, this value will be interpreted as 120 pixels.
More recent browsers support the following additional units of measurements (Internet Explorer 5.0 and later supports all of these units):
cmCentimeters.
emSize relative to parent element's size. For example, 2em is twice the size of the parent element.
exFont size relative to the size of the parent font's lowercase x. For example, a font with the size 2ex is twice the size of the lowercase x in the parent font.
inInches.
mmMillimeters.
%Percentage.
pcA pica represents 12 points.
pxPixels (the default value).
ptPoints (1/72 of an inch).
Again, not all properties support all units. Furthermore, not all browsers support all these units.