Controls for Microsoft Visual Basic .NET and Microsoft Visual Studio .NET Exam 70-305
Date: Oct 17, 2003
Terms you'll need to understand:
- CSS (cascading style sheets)
- HTML controls
- HTML server controls
- Input validation
- Web server controls
Techniques you'll need to master:
- Adding controls to ASP.NET pages
- Customizing control appearance and behavior by setting properties
- Dynamically loading controls at runtime
- Using cascading style sheets to customize the look of a Web site
- Validating user input
Controls are the building blocks of a graphical user interface (GUI). Visual Studio .NET allows you to work with the following types of controls on Web Forms:
-
HTML ControlsTraditional HTML elements displayed as controls.
-
HTML Server ControlsHTML elements that can be programmed on the server, marked with the runat="server" attribute.
-
Web Server ControlsThese new controls are specifically designed to integrate well with the ASP.NET programming model. They support data binding and other advanced capabilities and might render as multiple HTML controls.
-
Validation ControlsValidation Controls are Web server controls that contain logic to validate input in other server controls.
-
Web User Controls and Web Custom ControlsThese are two types of controls that you can create yourself. You can learn more about these controls in Chapter 8, "Creating and Managing Components and .NET Assemblies."
HTML Controls
HTML controls represent common HTML elements. You can access all the commonly used HTML controls through the HTML tab in the Visual Studio .NET Toolbox. You can drag these controls to a Web Form and set their properties in the Properties window.
Controls from the HTML tab of the Toolbox such as Text Field and Label are converted to their appropriate HTML equivalent such as <INPUT> and <DIV> elements, respectively, in the source code of the ASPX file. All the HTML controls are automatically placed inside an HTML <FORM> element. These controls are saved exactly as they'll appear when they're sent to the user's browser.
You probably won't make much use of HTML controls on ASP.NET Web forms. That's because there's no good way to programmatically interact with these controls from your Visual Basic .NET controls. ASP.NET provides two other sets of controls that are much better suited for server-side programming: HTML Server controls and Web Server controls.
HTML Server Controls
You can mark any HTML control to run as an HTML server control. Unlike regular HTML controls, HTML server controls are programmable on the Web server. You can access properties and events for the HTML server control just as you do for controls in Windows desktop-based applications.
HTML server controls are not as flexible in code as are Web Server controls. The main reason they exist is that they provide an easy migration path for existing HTML pages. To convert an HTML control to an HTML server control, right-click on it in Visual Studio .NET and select Run As Server Control.
Web Server Controls
Web server controls provide a higher level of abstraction than HTML server controls because their object model matches closely with the .NET Framework, rather than matching with the requirements of HTML syntax. In the HTML source for your page, Web server controls are represented as XML tags rather than as HTML elements. But remember, the browser receives standard HTML in any case.
Web server controls have a number of advanced features:
Web server controls provide a rich object model that closely matches with the rest of the .NET Framework.
Web server controls have built-in automatic browser detection capabilities. They can render their output HTML correctly for both uplevel and downlevel browsers.
Some Web server controls have the capability to cause an immediate postback when users click, change, or select a value.
Some Web server controls (such as the Calendar and AdRotator controls) provide richer functionality than is available with HTML controls.
NOTE
ASP.NET treats browsers as either uplevel or downlevel. Uplevel browsers support HTML 4.0 or later, the Microsoft Document Object Model (DOM), Cascading Style Sheets, and JavaScript 1.2 or later. Internet Explorer 4.0 or later is an example of an uplevel browser. Browsers with any lesser capabilities are considered to be down-level browsers.
Web server controls are declared in HTML explicitly by prefixing the classname of the Web server control with asp: and of course including the runat="server" attribute in its definition, creating an XML tag in the asp namespace. For example, a Label Web server control can be declared in code as <asp:Label runat="server">. If you are using Visual Studio .NET, you can just drag and drop these controls on a Web Form using the Web Forms tab of the Visual Studio .NET Toolbox.
Most of the Web server controls derive their functionality by inheriting from the WebControl class of the System.Web.UI.WebControls namespace. However, some Web server controls such as the Repeater and XML controls do not get their functionality from the WebControl class; they instead derive directly from the Control class of the System.Web.UI namespace.
Table 3.1 lists some of the common properties that all Web server controls derive from the WebControl class.
Table 3.1 Important Properties of the System.Web.UI.WebControls.WebControl Class
Properties |
Description |
AccessKey |
Specifies the single character keyboard shortcut key for quick navigation to the Web server control. The focus is moved to the Web server control when the Alt+AccessKey assigned to this property is pressed. |
BackColor |
Specifies the background color of the Web server control. |
BorderColor |
Specifies the border color of the Web server control. |
BorderStyle |
Specifies the border style of the Web server control. |
BorderWidth |
Specifies the border width of the Web server control. |
Controls |
Represents the collection of controls added to the Web server control as child controls. |
CssClass |
Represents the CSS class with which the Web server control is rendered. |
Enabled |
Indicates whether the Web server control is allowed to receive the focus. |
EnableViewState |
Indicates whether view state is enabled for the Web server control. |
Font |
Specifies a FontInfo object that represents the font properties of a Web server control. |
ForeColor |
Specifies the color of text in the Web server control. |
Height |
Specifies the height of the Web server control. |
ID |
Specifies an identifier for the Web server control. |
Parent |
Represents the parent control of the Web server control. |
Style |
Specifies the collection of CSS properties applied to the Web server control. |
TabIndex |
Specifies the tab order of a Web server control. |
ToolTip |
Specifies the pop-up text displayed by the Web server control when the mouse hovers over it. |
Visible |
Indicates whether the Web server control is visible. |
Width |
Specifies the width of the Web server control. |
Common Web Server Controls
The following sections discuss some simple but commonly used controls. These controls have a small number of properties, and they are usually rendered as a single HTML element.
The Label Control
A Label control is used to display read-only information to the user. It is generally used to label other controls and to provide the user with any useful messages or statistics. It exposes its text content through the Text property. This property can be used to manipulate its text programmatically. The control is rendered as a <span> HTML element on the Web browser.
The TextBox Control
A TextBox control provides an area that the user can use to input text. Depending on how you set the properties of this Web server control, you can use it for single or multiline text input, or you can use it as a password box that masks the characters entered by the user with asterisks or bullets, depending on the browser. Thus, this server control can be rendered as three different types of HTML elements<input type="text">, <input type="password">, and <textarea>. Table 3.2 summarizes the important members of the TextBox class.
Table 3.2 Important Members of the TextBox Class
Member |
Type |
Description |
AutoPostBack |
Property |
Indicates whether the Web Form should be posted to the server automatically whenever the data in the text box is changed. |
Columns |
Property |
Specifies the width in characters of the text box. |
MaxLength |
Property |
Specifies the maximum number of characters that may be entered by the user. The default value is 0, which does not impose any limit. |
ReadOnly |
Property |
Indicates whether the contents of the text box are read-onlythat is, they cannot be modified. The default value is False. |
Rows |
Property |
Specifies the height in characters of a multiline text box. The default value is 0. Works only if the TextMode property is set to MultiLine. |
Text |
Property |
Specifies the text contained in the text box. |
TextChanged |
Event |
Occurs when the value of the Text property changes. TextChanged is the default event for the TextBox class. |
TextMode |
Property |
Represents the type of the text box to be rendered in the Web page. It can be displayed in one of the three values of the TextBoxMode enumerationMultiLine (text box can accept multiple lines of input), Password (single-line text box with each character masked with an asterisk character, *) and SingleLine (single-line text box with normal text displayed). |
Wrap |
Property |
Specifies whether the control will automatically wrap words to the next line. The default value is True. Works only if the TextMode property is set to MultiLine. |
The Image Control
The Image Web server control can display images from BMP, JPEG, PNG, and GIF files. The control is rendered as an <img> HTML element on the Web page. Table 3.3 summarizes the important properties of the Image class.
Table 3.3 Important Members of the Image Class
Properties |
Description |
AlternateText |
Specifies the text that is displayed in the place of the Image Web server control when the image cannot be displayed. |
ImageAlign |
Indicates the alignment of the Image Web server control with reference to other elements in the Web page. |
ImageUrl |
Represents the URL of the image that the Image Web server control displays. The URL can be relative or absolute. |
The CheckBox and RadioButton Controls
A CheckBox control allows you to select one or more options from a group of options, and a group of RadioButton controls is used to select one out of several mutually exclusive options. The RadioButton controls that need to be set mutually exclusive should belong to the same group specified by the GroupName property. The check box and radio button Web server controls are rendered as <input type="checkbox"> and <input type="radio"> HTML elements on the Web page.
The RadioButton class inherits from the CheckBox class, and both of them share the same members, except for the GroupName property available in the RadioButton class.
Table 3.4 summarizes the important members of the CheckBox and RadioButton classes.
Table 3.4 Important Members of the CheckBox and RadioButton Classes
Member |
Member |
Description |
AutoPostBack |
Property |
Indicates whether the Web Form should be posted to the server automatically when the check box is clicked. |
Checked |
Property |
Returns True if the check box or radio button has been checked. Otherwise, it returns False. |
CheckedChanged |
Event |
Occurs every time a check box is checked or unchecked. CheckedChanged is the default event for the CheckBox class. |
GroupName (RadioButton class only) |
Property |
Specifies the group to which this control belongs. |
Text |
Property |
Specifies the text displayed along with the check box. |
TextAlign |
Property |
Specifies the alignment of the text displayed along with the check box. |
The Button, LinkButton, and ImageButton Controls
There are three types of button Web server controls. Each of these controls is different in its appearance and is rendered differently on the Web page:
ButtonThe Button control displays as a push button on the Web page and is rendered as an <input type="submit"> HTML element.
LinkButtonThe LinkButton control displays as a hyperlink on the Web page and is rendered as an <a> HTML element.
ImageButtonThe ImageButton control displays as an image button on the Web page and is rendered as an <input type="image"> HTML element.
NOTE
The LinkButton control works only if client-side scripting is enabled in the Web browser.
All three of these controls post the form data to the Web server when they are clicked. Table 3.5 summarizes the important members that are applicable to the Button, LinkButton, and ImageButton classes.
Table 3.5 Important Members of the Button, LinkButton, and ImageButton Classes
Member |
Type |
Description |
CausesValidation |
Property |
Indicates whether validation should be performed when the button control is clicked. |
Click |
Event |
Occurs when the button control is clicked. Click is the default event of all three classes. This event is mostly used for submit buttons. |
Command |
Event |
Occurs when the button control is clicked. This event is mostly used for command buttons. The event handler receives an object of type CommandEventArgs that contains both the CommandName and CommandArgument properties containing event-related data. |
CommandArgument |
Property |
Specifies the argument for a command. Works only if the CommandName property is set. The property is passed to the Command event when the button is clicked. |
CommandName |
Property |
Specifies the command name for the button. The property is passed to the Command event when the button is clicked. |
Text |
Property |
Specifies the text displayed on a button. The ImageButton class does not have this property. |
All three button controls can behave in two different waysas a submit button or as a command button. By default, any type of button Web server control is a submit button. If you specify a command name via the CommandName property, the button controls also become a command button.
A command button raises the Command event when it is clicked. The button passes the CommandName and CommandArgument encapsulated in a CommandEventArgs object to the event handlers. A command button is useful when you want to pass some event-related information to the event handler.
Event Handling with Web Server Controls
One key feature of many ASP.NET Web applications is the easy interactivity that they offer to the user. In most cases, handling events plays an important part in this interactivity. Although the user is working with the rendered HTML in his own browser, Web Server controls allow you to handle events with code that's executed on the server.
Web server controls have a set of intrinsic events available to them. The name and number of these events depend on the type of the Web server control. By convention, all events in the .NET Framework pass two arguments to their event handlerthe object that raised the event and an object containing any event-specific information.
Code on the server can't execute until the page is sent back to the server, which is known as postback. Some events are cached and are fired on the Web server at a later stage when the page is posted back as a result of a click event. Some Web server controls (for example, the DropDownList) have a property named AutoPostBack. When this property is set to True, it causes an immediate postback of the page when the value of the control is changed.
Some advanced Web server controls such as the DataGrid control can also contain other controls such as a Button. DataGrid controls usually display dynamically generated data, and if each row of DataGrid contains a Button, you might end up having a variable number of Button controls. Writing an individual event handler for each Button control in this case is a very tedious process. To simplify event handling, controls such as DataGrid support bubbling of events in which all events raised at the level of child control are bubbled up to the container control, where the container control can raise a generic event in response to the child events.
CAUTION
For the most part, Web server control events are processed by server code. You can also use client code such as JScript to process Web server control events. To do so, you need to dynamically add the client code method name to the control. For example, the following code fragment attaches the someClientCode() client-side method to the onMouseOver event of the btnSubmit button.
btnSubmit.Attributes.Add("onMouseOver", _ "someClientCode();")
The List Controls
The category of list controls consists of the DropDownList, ListBox, CheckBoxList, and RadioButtonList controls. These controls display a list of items from which the user can select. These controls inherit from the abstract base ListControl class. The class provides the basic properties, methods, and events common to all the list controls. Table 3.6 summarizes the important members of the ListControl class with which you should be familiar.
Table 3.6 Important Members of the ListControl Class
Member |
Member |
Description |
AutoPostBack |
Property |
Indicates whether the Web Form should be posted to the server automatically whenever the list selection is changed. Works only if the browser supports client-side scripting. |
Items |
Property |
Specifies a collection of items in the list control. |
SelectedIndex |
Property |
Specifies an index of the currently selected item. The default value is 1, which means that no item is selected in the list control. |
SelectedIndexChanged |
Event |
Occurs when the SelectedIndex property changes. SelectedIndexChanged is the default event for the list controls. |
SelectedItem |
Property |
Specifies the currently selected item. |
Although these controls inherit their basic functionality from the ListControl class, they display the list of items in different styles and support different selection modes.
A DropDownList Web server control allows you to select only a single item from the drop-down list. The DropDownList Web server control is rendered as a <select> HTML element, and its items are added as <option> elements within the HTML <select> element. The default value of the SelectedIndex property is 0, which means that the first item is selected in the drop-down list. This overrides the default of the general ListControl class.
A ListBox Web server control allows you to select single or multiple items from the list of items displayed in the list box. The ListBox Web server control is rendered as a <select> or <select multiple> HTML element, depending on whether single or multiple selections are allowed. The items are added as <option> elements within the HTML <select> element. The ListBox class adds two more properties to enable it to select multiple items:
RowsThis property represents the number of rows to be displayed in the list box. The default value is 4. The value of this property must be between 1 and 2000.
SelectionModeThis property indicates the mode of selection allowed in the list box. It can be one of the ListSelectionMode valuesMultiple or Single (default).
The CheckBoxList and RadioButtonList Web server controls display lists of check boxes and radio buttons, respectively, where each check box or radio button represents a CheckBox or RadioButton Web server control. The CheckBoxList control allows you to select multiple check boxes in the list. The RadioButtonList control allows you to select only a single radio button from the list of radio buttons. CheckBoxList and RadioButtonList render each list item as <input type="checkbox"> and <input type="radio"> HTML elements, respectively. The list items are displayed in a table or without a table structure depending on the layout selected.
NOTE
The default value of the SelectedIndex property in a list control is 1, which indicates that no item is selected in the list control. However, the DropDownList control overrides this property and sets the default value to 0, which indicates the first item in the list. This ensures that an item is always selected in the drop-down list.
CAUTION
ListBox and CheckBoxList allow you to make multiple selections from the list controls. When these controls allow multiple selections, the SelectedIndex and SelectedItem properties return the index of the first selected item and the first selected item itself, respectively. You have to iterate through the Items collection and check that each item's Selected property is true to retrieve the items selected by the user.
CAUTION
The IsPostBack property can be used to ensure that code behind a Web Form only runs when the page is first loaded. IsPostBack is False when the page is first loaded and True whenever it is reloaded (for example, in response to the user clicking a command button).
The PlaceHolder and Panel Controls
A PlaceHolder Web server control allows you to hold an area on a Web page. The PlaceHolder control allows you to add controls dynamically in a Web page in the area reserved by the PlaceHolder control. This control inherits from the System.Web.UI.Control class and does not share the common properties shared by the Web server controls that inherit from the WebControl class. The control does not define any new properties, events, or methods. It does not render any HTML element for itself.
A Panel Web server control acts as a container for other controls in the Web page. The Panel control can be used to organize controls in the Web page. It can be used to hide or show controls contained in the panel on the Web page. Controls can also be added programmatically to the panel control.
The Panel Web server control is rendered as a <div> HTML element on the Web page. Table 3.7 summarizes the important members of the Panel class with which you should be familiar.
Table 3.7 Important Members of the Panel Class
Member |
Member |
Description |
BackImageUrl |
Property |
Specifies the URL of the background image to be displayed behind the contents of the Panel control. |
HorizontalAlign |
Property |
Specifies the horizontal alignment of the contents within the Panel control. |
Wrap |
Property |
Indicates whether the contents in the panel can automatically wrap within the panel. The default value is True. |
The Panel control is especially useful when you want to create controls dynamically. To see how this works, follow these steps:
Add a new Web Form to your Web Application.
Place a TextBox control, a Button control, and a Panel control on the Web Form. Set the ID property of the TextBox control to txtCount. Set the ID property of the Button control to btnCreate. Set the ID property of the Panel control to pnlDynamic.
Double-click the Button control. This will open the code view of the Web Form and display a blank event handler for the Button control's Click event. Add this code to the Click event:
Click the Save button on the Visual Studio .NET toolbar to save the Web Form.
Select Debug, Start to open the Web Form in a browser.
Enter a numeral in the TextBox and click the Button control. The form will post back to the server. After a brief delay, the server will deliver the new page with the dynamic controls on it.
Private Sub btnCreate_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles btnCreate.Click ' Parse the TextBox contents into an integer Dim intControls As Integer = _ Convert.ToInt32(txtCount.Text) ' Create that many TextBox controls Dim i As Integer Dim txt(intControls) As TextBox For i = 1 To intControls txt(i) = New TextBox() ' Set the id property of the textbox txt(i).ID = String.Format("DynamicBox{0}", i) ' Add the textbox to the panel ' if you omit this step, the textbox is ' created but not displayed pnlDynamic.Controls.Add(txt(i)) Next End Sub
CAUTION
When you dynamically create a control, you must remember to add it to one of the container controls on the Web page. If you just create a control but forget to add it to the container control, your control will not be rendered with the page.
The Table, TableRow, and TableCell Controls
You can use the Table, TableRow, and TableCell controls to build a table on the Web page. The Table control is rendered as a <table> HTML element on the Web page. Table 3.8 summarizes the important members of the Table class with which you should be familiar.
Table 3.8 Important Members of the Table Class
Member |
Member |
Description |
BackImageUrl |
Property |
Specifies the URL of the background image to be displayed behind the contents of the table. |
CellPadding |
Property |
Specifies the distance in pixels between the border and the contents of a cell in the table control. |
CellSpacing |
Property |
Specifies the width in pixels between the cells of the Table control. |
GridLines |
Property |
Indicates which cell borders will be displayed in the Table control. |
HorizontalAlign |
Property |
Specifies the horizontal alignment of the table within the Web page. |
Rows |
Property |
-Specifies a collection of rows in the Table control. |
The TableRow class represents a row in a Table control. The TableRow class is rendered as a <tr> HTML element on the Web page. Table 3.9 summarizes the important members of the TableRow class with which you should be familiar.
Table 3.9 Important Members of the TableRow Class
Member |
Member |
Description |
Cells |
Property |
Specifies a collection of the table cells contained in a table row. |
HorizontalAlign |
Property |
Specifies the horizontal alignment of the cells within the table row. |
VerticalAlign |
Property |
Specifies the vertical alignment of the cells within the table row. |
The TableCell Web server control represents a cell in a Table control. The Table Web server control is rendered as a <td> HTML element on the Web page. Table 3.10 summarizes the important members of the TableCell class with which you should be familiar.
Table 3.10 Important Members of the TableCell Class
Member |
Member |
Description |
ColumnSpan |
Property |
Specifies the number of columns occupied by a single table cell. |
HorizontalAlign |
Property |
Specifies the horizontal alignment of the contents of the cells within the table cell. |
RowSpan |
Property |
Specifies the number of rows occupied by a single table cell. |
Text |
Property |
Specifies the text displayed in a table cell. |
VerticalAlign |
Property |
Specifies the vertical alignment of the cells within the table row. |
Wrap |
Property |
Indicates whether the contents in a cell can automatically wrap to the next line. |
The AdRotator Control
The AdRotator Web server control provides a convenient mechanism for displaying advertisements randomly selected from a list on a Web page. It fetches the images from a list stored in an Extensible Markup Language (XML) file and randomly loads an image in the AdRotator control every time the page is loaded. It allows you to specify a Web page whose contents will be displayed in the current window when the AdRotator control is clicked. The ad files used by the AdRotator control follow this format:
<?xml version="1.0" ?> <Advertisements> <Ad> <ImageUrl>que.gif</ImageUrl> <NavigateUrl>http://www.quepublishing.com </NavigateUrl> <AlternateText>Que Publishing</AlternateText> <Impressions>40</Impressions> <Keyword>Books</Keyword> </Ad> <Ad> ... </Ad> ... </Advertisements>
The AdRotator control is rendered as an anchor HTML element, <a>, with an embedded image HTML element, <img>, to display the image on the Web page.
The Calendar Control
The Calendar Web server control displays a calendar on the Web page. It allows you to select a day, a week, a month, or even a range of days. You can customize the appearance of the control and even add custom content for each day. The control generates events when a selection changes or when the visible month is changed in the Calendar control. The Calendar control is rendered as a <table> HTML element on the Web page.
Tables 3.11 and 3.12 summarize the important properties and events of the Calendar class, respectively.
Table 3.11 Important Properties of the Calendar Class
Properties |
Description |
CellPadding |
Specifies the distance in pixels between the border and the contents of a cell in the Calendar control. |
CellSpacing |
Specifies the width in pixels between the cells of the Calendar control. |
DayHeaderStyle |
Specifies the style properties of the section where the days of the week are displayed. Works only if the ShowDayHeader property is True. |
DayNameFormat |
Specifies the name format for the days of the week. |
DayStyle- |
Specifies the style properties of the section where the days of the displayed month are displayed. |
FirstDayOfWeek |
Specifies the day of the week to be displayed in the first column of the Calendar control. |
NextMonthText |
Specifies the text for the navigational element to select the next month. The default value is >, the HTML code for the greater-than (>) sign. Works only if the ShowNextPrevMonth property is True. |
NextPrevFormat |
Specifies the text format for the navigational elements that select the previous and next months on the Calendar control. |
NextPrevStyle |
Specifies the style properties for the next and previous navigational elements. Works only if the ShowNextPrevMonth property is True. |
OtherMonthDayStyle |
Specifies the style properties for the days that do not belong to the displayed month. |
PrevMonthText |
Specifies the text for the navigational element to select the previous month. The default value is <, the HTML code for the less-than (<) sign. Works only if the ShowNextPrevMonth property is True. |
SelectedDate |
Specifies the selected date. |
SelectedDates |
Specifies a collection of selected dates. |
SelectedDayStyle |
Specifies the style properties for the selected day in the Calendar control. |
SelectionMode |
Specifies the mode of selection in the calendar. |
SelectMonthText |
Specifies the text for the month selection element in the selector column. The default value is >>. Works only if the SelectionMode property is DayWeekMonth. |
SelectorStyle |
Specifies the style properties for the week and month selector column. Works only if the SelectionMode property is DayWeek or DayWeekMonth. |
SelectWeekText |
Specifies the text for the week selection element in the selector column. The default value is >. Works only if the SelectionMode property is DayWeek or DayWeekMonth. |
ShowDayHeader |
Indicates whether the row showing the name of the day of the week should be displayed. The default is True. |
ShowGridLines |
Indicates whether the cells of the Calendar control should be separated with grid lines. The default is False. |
ShowNextPrevMonth |
Indicates whether the navigational elements for the next and previous month should be displayed. The default is True. |
ShowTitle |
Indicates whether to show the title of the Calendar control. |
TitleFormat |
Specifies the format of the title of the Calendar control. Values are specified by the TitleFormat enumerationMonth and MonthYear (default). Works only if the ShowTitle property is True. |
TitleStyle |
Specifies the style properties for the title of the Calendar control. Works only if the ShowTitle property is True. |
TodayDayStyle |
Specifies the style properties for today's date in the calendar control. |
TodaysDate |
Specifies today's date. The default is picked up from the system. |
VisibleDate |
Specifies the month to be displayed on the calendar depending on the value of this property. |
WeekendDayStyle |
Specifies the style properties for the weekend days in the Calendar control. |
Table 3.12 Important Events of the Calendar Class
Event |
Description |
DayRender |
Occurs when each day is created in the Calendar control. This event occurs after the control is created but before it is rendered to the Web page. |
SelectionChanged |
Occurs when the user changes the selection in the Calendar control. SelectionChanged is the default event for the Calendar control. |
VisibleMonthChanged |
Occurs when the month selection is changed when the user clicks the previous or next month navigational elements. |
User Input Validation
ASP.NET provides a set of Web server controls called validation controls. These controls provide sophisticated validation on both the client side and the server side depending on the validation settings and the browser capability.
NOTE
The client-side validation provided by ASP.NET validation controls works only with Internet Explorer 4.0 or higher.
CAUTION
ASP.NET ensures that validations are performed on the server side even if they were already performed at the client side. This ensures that validations are not bypassed if a malicious user tries to circumvent the client-side validation. Of course, if the client-side validation fails, the server-side validation is never performed.
The validation controls are usually associated with input server controls on which the validation needs to be performed. For validation to work properly, the validation control and the input server control must be placed in the same container control.
All the validation controls derive their basic functionality from the BaseValidator abstract class available in the System.Web.UI.WebControls namespace. Table 3.13 lists some of the important members of the BaseValidator class that are inherited by the validation controls.
Table 3.13 Important Members of the BaseValidator Class
Member |
Type |
Description |
ControlToValidate |
Property |
Specifies the id of the input server control that needs to be validated. |
Display |
Property |
Specifies how to display the inline error message contained in the Text property. It can be any of the ValidatorDisplay valuesDynamic (the space is dynamically added), None (the message is never displayed), and Static (the space is occupied when the validation control is rendered). |
EnableClientScript |
Property |
Indicates whether the client-side validation is enabled. The default is True. |
Enabled |
Property |
Indicates whether the validation control is enabled. If False, the validation is never performed. |
ErrorMessage |
Property |
Represents the error message to be displayed when the validation fails by the ValidationSummary control. If the Text property is not set, this message is displayed inline. |
ForeColor |
Property |
Specifies the foreground color in which the message is displayed when the validation fails. The default value is Color.Red. |
IsValid |
Property |
Indicates whether the input control passes the validation. |
Text |
Property |
Specifies the text of the error message that is displayed by the validation control inline. |
Validate |
Method |
Performs the validation on the associated input control, and then updates the IsValid property with the result of validation. |
Each validation control maintains an IsValid property that indicates the status of the validation test. The Page control that hosts all the Web controls also contains a property called IsValid that indicates the status of the validation for the whole page. When each validation control on the Web Form sets its IsValid property to True, the Page.IsValid property also becomes True. If any control has its IsValid property set to False, Page.IsValid will also return False.
ASP.NET provides five validation controls that derive their functionality from the BaseValidator class:
RequiredFieldValidatorEnsures that the data is not empty in the input control.
RegularExpressionValidatorEnsures that the data in the input control matches a specific pattern.
RangeValidatorEnsures that the data is within a specific range in the input control.
CompareValidatorCompares the data against a given value.
CustomValidatorUses custom logic to validate data.
You can associate any number of validation controls with a single input server control. For example, the Date of Hire input field in an Add Employee form cannot be left empty (validated through the RequiredFieldValidator control) and should be less or equal to the current date (validated through the CompareValidator control) .
The RequiredFieldValidator Control
The RequiredFieldValidator control can be used to check whether the input control contains an entry. It makes the associated input control a required field in the Web page and ensures that some input data is passed to it. The control also trims whitespace in order to check for the required field entry.
The RequiredFieldValidator control contains a special property called InitialValue that can be passed the initial value of the associated input control. During validation, if the input control's validation property contains the same initial value or is empty, it sets the IsValid property to False, indicating that the validation failed. For example, a drop-down list may allow users to select a state. When the page loads, the initial value in this control might be Select a State. If a RequiredFieldValidator control is associated with the drop-down list control, its InitialValue property can be set to the same initial value as the drop-down list, Select a State. When the validation occurs, the validation control will ensure that the item selected in the drop-down list is not the item set in the InitialValue property of the validation control.
The RegularExpressionValidator Control
The RegularExpressionValidator control checks whether the associated input control's validation property matches a specified pattern. This pattern is specified by the ValidationExpression property using a regular expression. If you're not familiar with regular expressions, you can find more information in the .NET Framework documentation.
The RangeValidator Control
The RangeValidator control is used to check whether the input control contains a value in a specified range. You can check the range of values against different data types such as String, Date, and Integer.
Table 3.14 shows the important properties of the RangeValidator class.
Table 3.14 Important Properties of the RangeValidator Class
Property |
Description |
MaximumValue |
Specifies the upper value of the validation range. |
MinimumValue |
Specifies the lower value of the validation range. |
Type |
Specifies the data type to be used when comparing the data. |
The CompareValidator Control
The CompareValidator control is used to compare the input server control's value against another value. The CompareValidator control can compare against a value specified to the validator control or against the value of another input control. The comparison can be made with different comparison operators such as equal, greater than, and so on. A special comparison operation can be made to verify that the associated input control's value is of a specified data type. You can make comparisons against different data types such as String, Date, and Integer.
Table 3.15 shows the important properties of the CompareValidator class.
Table 3.15 Important Properties of the CompareValidator Class
Property |
Description |
ControlToCompare |
Specifies the input server control against whose value the associated input control is to be validated. |
Operator |
Specifies the comparison operation to be performed. |
Type |
Specifies the data type to be used when comparing the data. |
ValueToCompare |
Specifies the value against which the associated input control is to be validated. |
The CustomValidator Control
The validation controls discussed allow you to handle many different types of validations. However, you might want to perform a validation that cannot be achieved by any of these validation controls. The CustomValidator control allows you to build a validation control for a custom specification. You can perform any custom validation both at the server-side and client-side with the help of this validation control.
The validation control exposes a property called ClientValidationFunction that specifies the name of the client script function to be executed for validation on the client side. This custom validation function will be passed two argumentsthe first is the custom validator control, and the second argument is an object containing two properties: IsValid and Value. The Value property contains the value that is to be validated and IsValid property is used to return the result of the validation.
At the server side, during the validation on the server, the validation control fires a ServerValidate event. An event handler containing the custom validation code is added to this event to perform validation on the server. The event sends a ServerValidateEventArgs object containing event-related data. This object contains two propertiesIsValid and Value. The Value property contains the value of the control that is to be validated, and the IsValid property is used to set the result of the validation.
The ValidationSummary Control
As the name implies, the ValidationSummary control is used to display a summary of all the validation errors on a Web page. It displays the ErrorMessage property of the validation controls in the summary. If the ErrorMessage property is not set, the Text property is displayed as error messages for all the validation controls whose validation fails.
Table 3.16 shows the important properties of the ValidationSummary class.
Table 3.16 Important Properties of the ValidationSummary Class
Property |
Description |
DisplayMode |
Specifies the way in which the validation summary will be displayed. |
EnableClientScript |
Indicates whether the client-side validation is enabled. The default is True. |
ForeColor |
Specifies the foreground color in which the message is displayed when the validation fails. The default value is Color.Red. |
HeaderText |
Specifies the header text of the validation summary control. |
ShowMessageBox |
Indicates whether the validation summary messages should be displayed in a message box. The default is False. |
ShowSummary |
Indicates whether the validation summary messages should be displayed inline in the validation summary control. The default is True. |
Cascading Style Sheets
A cascading style sheet (CSS) contains style definitions that are applied to elements in an HTML document. The information inside a CSS defines how HTML elements are displayed and where they are positioned on a Web page. CSS makes it easy to achieve a uniform look and feel across your Web application.
Both HTML server controls and Web server controls provide first-class support for CSS styles. In addition to this, Visual Studio .NET provides GUI-based style-editing tools, which makes it easy to work with CSS files.
NOTE
CSS is generally only supported by Web browsers that support HTML 4.0 or higher. Older Web browsers that support only HTML 3.2 or earlier simply ignore CSS styles.
When you create a Web application using Visual Basic .NET, Visual Studio .NET automatically creates a default style sheet named Styles.css for your Web application. You can also add additional style sheets for specific documents. You can modify the built-in styles or add new styles that are then associated with particular controls and elements.
To see how Visual Studio .NET lets you work with cascading style sheets, follow these steps:
-
Add a new Web Form to your Web Application.
-
Add a Label control and a TextBox control to the Web Form.
-
Type some text in the Text property of the Label control. Set the CssClass property of the Label control to MyLabelClass and set the CssClass property of the TextBox control to MyTextBoxClass.
-
Switch to the HTML view of the Web Form and add the following code inside of the HTML <HEAD> element:
-
Double-click the Styles.css file in Solution Explorer to open it. Then click the CSS Outline tab at the bottom of the Toolbox.
-
In the Style Sheet Outline in the Toolbox, right-click on the Classes folder, and select Add Style Rule.
-
In the Add Style Rule dialog box, select the Class Name radio button. Enter MyLabelClass as the classname and click the > button. Click OK to create the class. Repeat these steps to create the MyTextBoxClass style.
-
Locate the code for MyLabelClass in the Styles.css file. Right-click inside this code and select Build Style. This will open the Style Builder dialog box, shown in Figure 3.1.
-
In the Style Builder dialog box, set the font color to Blue and set the size to 2 em. Click OK to create the style.
-
Locate the code for MyTextBoxClass. Right-click inside this code and select Build Style.
-
Select the Background tab and set the background color to Lime. Select the Text tab and set the horizontal alignment to Right. Click OK.
-
Set the Web Form as the start form for the project.
-
Run the project. You'll see your font and color choices applied to the controls on the Web Form.
<LINK href="Styles.css" type="text/css" rel="stylesheet">
Figure 3.1 The Style Builder dialog box.
Exam Prep Questions
Question 1
You are designing a new page for your ASP.NET Web Application from scratch. The page will display statistical information in a series of tables and text fields, but will not require any user input. The page will carry out complex calculations to determine the validity of the information that it displays. Which controls should you use to build the user interface for this page?
-
HTML controls
-
HTML server controls
-
Web server controls
-
Validation controls
Answer C is correct. Web server controls are designed for easy programmability on ASP.NET pages. Answer A is incorrect because you can't use code-behind to easily specify the values to display in HTML controls. Answer B is incorrect because HTML server controls are mainly used to upgrade existing ASP pages, not to create new pages. Answer D is incorrect because validation controls are only useful when there is user input to validate.
Question 2
You have developed an ASP.NET Web Form that allows users to select from a list of replacement parts to order. The Web Form uses the following code to load the list into a control:
Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load lbParts.Items.Add("Flange") lbParts.Items.Add("Motor") lbParts.Items.Add("Bracket") End Sub
As users select parts, you execute code on the Web server to move the selected parts to a second list. Users report that the page initially displays correctly, but after they select one part, the original list reads as follows:
Flange Motor Bracket Flange Motor Bracket
How should you modify the code to prevent this from happening?
-
Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load If lbParts.Items.Count < 3 Then lbParts.Items.Add("Flange") lbParts.Items.Add("Motor") lbParts.Items.Add("Bracket") End If End Sub
-
Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load If Not IsPostBack Then lbParts.Items.Add("Flange") lbParts.Items.Add("Motor") lbParts.Items.Add("Bracket") End If End Sub
-
Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load If IsPostBack Then lbParts.Items.Add("Flange") lbParts.Items.Add("Motor") lbParts.Items.Add("Bracket") End If End Sub
-
Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load lbParts.Items.Clear lbParts.Items.Add("Flange") lbParts.Items.Add("Motor") lbParts.Items.Add("Bracket") End Sub
Answer B is correct. You can use the IsPostBack property to tell whether the page is being loaded for the first time and then only perform initializations on the first load. Answers A and D are incorrect because they will reinitialize the ListBox every time that the page is loaded, slowing down the page rendering. Answer C is incorrect because the postback test should be looking for False, not True.
Question 3
You have designed a Web Form that includes a Panel control named Panel1. Under some circumstances, you want to dynamically display a TextBox control on this Panel control. Your form includes the following code:
Dim txtNew As TextBox = New TextBox txtNew.ID = "txtNew" txtNew.Text = "Dynamic TextBox"
When you run the code, the form does not display the new TextBox. You single-step through the code and verify that these lines are being executed. How should you fix this problem?
-
Dim txtNew As TextBox = New TextBox txtNew.ID = "txtNew" txtNew.Text = "Dynamic TextBox" txtNew.Enabled = True
-
Dim txtNew As TextBox = New TextBox txtNew.ID = "txtNew" txtNew.Text = "Dynamic TextBox" txtNew.Visible = True
-
Dim txtNew As TextBox = New TextBox txtNew.ID = "txtNew" txtNew.Text = "Dynamic TextBox" Panel1.Controls.Add("txtNew")
-
Dim txtNew As TextBox = New TextBox txtNew.ID = "txtNew" txtNew.Text = "Dynamic TextBox" Panel1.Controls.Add(txtNew)
Answer D is correct. To show a dynamically created control on a Web Form, you must add the new control to the Controls collection of a container control such as a Panel. Answers A and B are incorrect because they alter the properties of the control without adding it to a container. Answer C is incorrect because the Add method requires an object reference, not a String with an object name.
Question 4
You are designing a Web page for your corporate intranet. All the users on the intranet are using either Internet Explorer 5.0 or Internet Explorer 6.0 as their browser. When an employee enters his employee number, you need to validate it as a legitimate employee number so that you can audit actions on the Web site. Which type of validation should you perform, if any?
-
You should not validate this data.
-
You should only perform client-side validation.
-
You should only perform server-side validation.
-
You should perform both client-side and server-side validation.
Answer D is correct. You should validate the data in this scenario because the correct data is critical to the application. You should use client-side validation because client-side validation is the fastest way to catch accidental errors in the data and can prevent bad data from reaching the server. However, you should also use server-side validation to eliminate the possibility of someone hand-crafting an HTTP request to bypass the client-side validation.
Question 5
You are designing a new home page for your company, using ASP.NET. The home page will have numerous graphics, including the company logo, images used for navigation, and pictures of your company's graphics. You want to make sure that users who cannot view graphics (for example, those browsing with a screen reader) receive a description of each image instead. Which property of the Image control should you set to provide this description?
-
Attributes property
-
ToolTip property
-
AlternateText property
-
ImageUrl property
Answer C is correct. The AlternateText property of an Image control supplies text that is used by screen readers and by other browsers when an image cannot be displayed. Answer A is incorrect because the Attributes property returns an array of attributes of the control. Answer B is incorrect because the ToolTip property only supplies text to be seen when the mouse is hovered over the control. Answer D is incorrect because the ImageUrl property tells the control which image to display.
Question 6
You are designing a Web Form that will allow the user to specify a date for a dental appointment. You want to allow the user to specify a date by choosing it from a calendar. The users of the application employ a wide variety of Web browsers, including Internet Explorer versions 3.2 through 6.0 and Netscape versions 4.79 through 7.0. How should you proceed to create this page with the least effort?
-
Work directly in HTML view of your Web form. Design the calendar using HTML tags.
-
Work in Design view of the Web form. Design the calendar by using the Table, TableRow, and TableCell Web server controls.
-
Work in Design view of the Web form. Design the calendar by using a single Calendar control.
-
Work in the code-behind file. Design the calendar by dynamically adding HTML controls to the Web Form at runtime.
Answer C is correct. ASP.NET will render complex controls such as the Calendar control properly for both uplevel and downlevel browsers by detecting the browser and sending the appropriate HTML markup. Answers A, B, and D are incorrect because they all require substantially more work than using a single Calendar control.
Question 7
Your company has an existing classic ASP application that is used to track news on your intranet. You have been tasked with upgrading the application to ASP.NET. As a first step, you want to keep the user interface the same, but move the business logic to code-behind files. How should you proceed?
-
Continue to use HTML controls on ASP.NET Web Forms. In the code-behind files, rewrite all business logic using Visual Basic .NET.
-
Use ASP.NET Web server controls instead of HTML controls. In the code-behind files, rewrite all business logic using Visual Basic .NET.
-
Apply the runat="server" attribute to all HTML controls. In the code-behind files, rewrite all business logic using Visual Basic .NET.
-
Continue to use HTML controls for labels and textboxes, but convert all button controls to Web server controls. In the code-behind files, rewrite all business logic using Visual Basic .NET.
Answer C is correct. Applying the runat="server" attribute is the only step required to make the controls on the page available to code in a code-behind file. Answers A and D are incorrect because you cannot use code-behind files to manipulate HTML controls. Answer B is incorrect because there is no built-in way to directly convert HTML controls to Web server controls.
Question 8
You are designing a Web Form that includes four RadioButton controls named rb1, rb2, rb3, and rb4. Users should be able to select either rb1 or rb2, and either rb3 or rb4. How should you configure the controls to achieve this?
-
Place rb1 and rb2 on a Panel control named pnlA. Place rb3 and rb4 on a Panel control named pnlB.
-
Set the GroupName property of rb1 and rb2 to "Group1". Set the GroupName property of rb3 and rb4 to "Group2".
-
Set the Parent property of rb2 to rb1. Set the Parent property of rb4 to rb3.
-
Set the AutoPostBack property of rb1 and rb3 to True. Set the AutoPostBack property of rb2 and rb4 to False.
Answer B is correct. RadioButton controls that share a GroupName are mutually exclusive. Answer A is incorrect because placing the controls on different panels organizes them visually, but does not put them in distinct groups. Answer C is incorrect because the Parent property is just a link to the form containing the controls. Answer D is incorrect because AutoPostBack indicates whether the Web Form should be posted when the control is clicked.
Question 9
You want to keep consistent formatting for all the Web Forms in your application. To achieve this, you have created a cascading style sheet named CompanyStyle.css and have linked it to all the Web pages. You have defined a style class named ButtonStyle in CompanyStyle.css to format buttons on the Web Forms. Which of the following property settings would you use with a Button Web server control to use the ButtonStyle style class?
-
Style="ButtonStyle"
-
Style=".ButtonStyle"
-
CssClass="ButtonStyle"
-
CssClass=".ButtonStyle"
Answer C is correct. The CssClass property specifies the CSS style class to apply to a particular control. Answers A and B are incorrect because the Style property is used to supply CSS attributes directly, rather than the name of a CSS style. Answers B and D are incorrect because styles are referred to without the leading dot, even though you must use the dot when defining them in a CSS file.
Question 10
You are designing a Web Form to collect user registration information for your corporate Web site. You want to ensure that users supply a value for the Age TextBox control and that the value supplied is between 18 and 105. Which validation control should you use (select all that apply)?
-
RequiredFieldValidator
-
RangeValidator
-
RegularExpressionValidator
-
CustomValidator
Answers A and B are correct. You can use the RequiredFieldValidator control to ensure that the user enters a value and the RangeValidator control to check that the value is in the correct range. Although you could use the RegularExpressionValidator or CustomValidator controls to check the range, doing so would require you to write a complex regular expression or custom business logic, so answers C and D are incorrect.
Question 11
Your Web Form displays a list of State names in a DropDownList control. As soon as the user selects a state, you want to update a Label control to display the appropriate sales tax rate. You have written custom logic to do so in the SelectedIndexChanged event handler for the control. What property should you set to ensure that this event is handled at the correct time?
-
EnableViewState = True
-
AutoPostBack = False
-
EnableViewState = False
-
AutoPostBack = True
Answer D is correct. By default, selection change events for list controls are not sent to the server until the Web Form is posted by some other means (for example, by the user clicking a Submit button). Setting the AutoPostBack property to True causes the postback to happen as soon as a new item is selected in the list. Answer B is incorrect because it uses the wrong AutoPostBack value. Answers A and C are incorrect because the EnableViewState property has no effect on the timing of postbacks.
Question 12
Your Web Form requires the user to enter an email address. Which control should you use to validate the contents of the TextBox containing the email address?
-
RequiredFieldValidator
-
RegularExpressionValidator
-
RangeValidator
-
CustomValidator
Answer B is correct. The RegularExpressionValidator control is suited to checking input that conforms to a particular pattern such as a date or an email address (and .NET has a built-in expression for email addresses). Answer A is incorrect because the RequiredFieldValidator ensures that data was entered, but does not check the contents of the data. Answer C is incorrect because the RangeValidator checks to see that data is between a pair of values. Answer D is incorrect because the CustomValidator requires you to write extra code to perform the same tasks that the RegularExpressionValidator has built in.
Need to Know More?
Liberty, Jesse and Hurwitz, Dan. Programming ASP.NET. O'Reilly, 2002.
Duthie, G. Andrew and MacDonald, Matthew. ASP.NET in a Nutshell. O'Reilly, 2002.
The .NET Framework Community Web site, http://www.gotdotnet.com.