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. |