Property Description ID Gets or sets a unique identifier to the HtmlAnchor control for reference at the server.. Name Gets or sets a unique identifier to the HtmlAnchor control for r
Trang 1Working with Controls C hap
The success of an application largely depends upon its user interface For an application to be successful, its interface needs to be attractive and easy-to-use Such a user interface can be designed by using various types of controls provided in ASP.NET
ASP.NET provides various types of controls that can be added to a Web form to make it interactive However, while developing an application, you may face a situation where the built-in controls do not fulfill your
requirements In such a situation, you need to create custom controls
This chapter provides an overview of the controls used in
an ASP.NET application It also discusses how to create custom controls and implement them in a Web
application
In this chapter, you will learn to:
Use ASP.NET Web Server controls
Create custom controls
Objectives
Trang 3ASP.NET solves this problem by providing server controls Server controls are the
fundamental building blocks that are specifically designed to work with Web forms in an ASP.NET application Server controls can be rendered as markup text on a Web browser and are capable of executing the program logic on the server Server controls also provide built-in methods and events This eliminates the need for writing the events and methods manually In addition, it provides security to the application because the program logic is executed on the Web server and only the result is sent back to the browser in the HTML format, thus, hiding the program logic from the user
Each server control provides an object-oriented programmable interface Therefore, each server control is an object with methods, properties, and events associated with it
Server controls can be viewed as special HTML tags, which are processed by the server The advantages of using server controls are:
Automatic state maintenance: ASP.NET server controls provide a property called
EnableViewState, which can be set to true to enable the server controls to maintain their state after a postback
Postback is the process by which a browser posts information back to itself It can also
be defined as the process by which a browser posts information back to the server by
requesting the same page
Browser independent rendering: When an ASP.NET page is requested, the server
generates the corresponding HTML code for all the server controls in the page The HTML code generated is specific to the Web browsers used by the clients This feature saves programmers from developing different versions of the page for different Web browsers
Easily programmable model: Server controls are implemented as objects in
ASP.NET This makes the server control programming model similar to the traditional object-oriented programming model, making it easy to program server controls
Using ASP.NET Web Server Controls
Trang 4Note
In addition to the server controls, ASP.NET provides HTML controls Most HTML
controls are similar to server controls However, there is a major difference Unlike
server controls, HTML controls are processed by the Web browser
To understand the processing of the server controls in a Web page, you need to
understand the sequence of their processing and how they are rendered on a Web page
The processing of a server control depends on two situations, whether the page is
requested for the first time by the client or it is posted back to the Web server when the user interacts with the Web page
When a page is requested for the first time, the server controls are processed in the
following sequence:
1 Initializing: The server creates an instance of the server control
2 Loading: The instance of the control is loaded onto the page object in which it is
defined
3 PreRendering: The control is updated with the changes made to it by the user This
phase prepares the control for rendering
4 Saving: The state information of the control is saved For example, if a value is set
for the control during the Load event, it is embedded in the HTML tag that will be returned to the browser
5 Rendering: The server creates the corresponding HTML tag for the control
6 Disposing: All cleanup tasks, such as closing files and database connections opened
by the control are performed
7 Unloading: All cleanup tasks, such as destroying the instances of server controls are
performed This is the final event in the life cycle of a server control
When the Web page is posted back to the Web server, the server controls are processed in the following sequence:
1 Initializing: The server creates an instance of the server control
2 Loading view state: The view state of the control, posted by the client, is reloaded
into the new instance of the control
3 Loading control instance: The instance of the control is loaded onto the page object
in which it is defined
4 Loading the postback data: The server searches any data corresponding to the
control that is loaded in the data posted by the client
Processing of Server Controls on a Web Page
Trang 55 PreRendering: The control is updated with the changes made in it by the user This
is done in preparation for rendering
6 Saving: The change in the state of the controls between the current request and the
previous request of the page is saved For each change, the corresponding event is raised For example, if the text of a textbox is changed, the new text is saved and a TextChanged event is raised
7 Rendering: The server creates the corresponding HTML tag for the control
8 Disposing: All cleanup tasks, such as closing files and database connections opened
by the control are performed
9 Unloading: All cleanup tasks like destroying the instances of server control are
performed This is the final event in the life cycle of a server control
The following figure illustrates the processing of a server control
Processing of a Server Control
Trang 6Note
In ASP.NET, Web page refers to an instance of the Page class and a Web form refers
to the Web page and all the controls on it
ASP.NET provides various types of server controls These controls can be classified into the following categories:
To overcome these limitations, ASP.NET provides the HTML server controls, which are processed by the Web server and make full use of the NET Framework utilities such as validation Some of the common HTML server controls are:
Trang 7HtmlAnchor Control
The HtmlAnchor control works like the HTML <a> tag but runs on the server It is used
to direct the user from one page to another The following table lists some properties of the HtmlAnchor control
Property Description
ID Gets or sets a unique identifier to the HtmlAnchor control for reference at
the server
Href Gets or sets the URL of the page to which the control is linked
Name Gets or sets a unique identifier to the HtmlAnchor control for reference at
the client side
Target Gets or sets the frame or window in which the page specified in the Href
property will load The default value is _self As a result the linked page will be loaded in the same window
Title Gets or sets the value of the tooltip attribute of the <a> tag that is displayed
when the mouse pauses over the control
Properties of the HtmlAnchor Control
When you click the HtmlAnchor control, the ServerClick event is raised Consider the following markup:
<a id="myAnchor1" href="URLLocation" runat="server">Click here</a>
<a id="myAnchor2" OnServerClick="myFunction" runat="server">Click here</a>
The preceding markup illustrates the HTML code of two HtmlAnchor server controls with the name myAnchor1 and myAnchor2, as specified by the id attribute When myAnchor1 is clicked, the browser navigates to the new location, URLLocation, as specified in the hrefattribute When myAnchor2 is clicked, the function, myFunction, attached to the
ServerClick event is invoked The OnServerClick attribute is used to attach an event handler to the ServerClick event
Trang 8HtmlInputText Control
The HtmlInputText control works like the HTML <input type="text"> tag but runs on the server The HtmlInputText server control is used to gather information from the user The following table lists some properties of the HtmlInputText control
at the client side
Size Gets or sets the width of the control
MaxLength Gets or sets the value for the maximum characters that can be entered in
the textbox
Value Gets or sets the value of the textbox or password box
Properties of the HtmlInputText Control
The commonly used method of the HtmlInputText control is OnServerChange The
OnServerChange method is invoked in response to the ServerChange event The
ServerChange event is triggered when either a new text message is entered or a change is made to the existing text in the HtmlInputText control The following markup illustrates the HTML code of two HtmlInputText controls:
<input type="text" id="txtName1" maxlength="12" runat="server">
<input type="text" id="txtName2" maxlength="15" runat="server">
The preceding markup illustrates the HTML code of two HtmlInputText server controls
with the names txtName1 and txtName2, as specified by the id attributes The txtName1can accommodate a maximum of 12 characters whereas txtName2 can accommodate a maximum of 15 characters, as specified by the maxlength attribute
HtmlInputCheckBox Control
The HtmlInputCheckBox control works as the HTML <input type="checkbox"> tag but runs on the server The HtmlInputCheckBox control is useful to implement questions that can have only two answers, such as yes/no or true/false For example, do you like Coffee? The answer is either yes or no
Trang 9The following table lists some properties of the HtmlInputCheckBox control
Property Description
ID Gets or sets a unique identifier to the HtmlInputCheckBox control for
reference at the server
Name Gets or sets a unique identifier to the HtmlInputCheckBox control for
reference at the client side
Checked Checks whether the check box is selected or not
Value Gets or sets the value of the HtmlInputCheckBox control
Properties of the HtmlInputCheckBox Control
When you select or clear a check box, the ServerChange event is raised The
ServerChange event triggers the associated event handler when the page consisting the
check box is submitted to the server The following markup illustrates the HTML code for the HtmlInputCheckBox control:
<input type="checkbox" id="MyCheckBox1"
OnServerChange="FunctionCheckBox" runat="server">
The preceding markup uses an HtmlInputCheckBox control named MyCheckBox1, as specified by the id attribute The OnServerChange attribute is used to attach an event
handler to the ServerChange event When the MyCheckBox1 HtmlInputCheckBox control
is selected or cleared, the FunctionCheckBox method attached to its ServerChange event
Trang 10The following table lists some properties of the HtmlInputRadioButton control
Property Description
ID Gets or sets a unique identifier to the HtmlInputRadioButton
control for reference at the server
Checked Gets or sets the status of the radio button This property will
return true if the radio button is selected
Name Sets the name of the option button group
Value Gets or sets the value of the HtmlInputRadioButton control
Properties of the HtmlInputRadioButton Control
When the HtmlInputRadioButton control changes its state from the previous state on the server, the ServerChange event is generated You can use the following markup to
implement the HtmlInputRadioButton control:
<input type="radio" id="MyRadioButton" name="GroupRadio"
value="Titanic" OnServerChange="FunctionRadio" runat="server">
ServerChange event
HtmlSelect Control
The HtmlSelect control is same as the HTML <select> element but it runs on the server This control is used to create a list box The HtmlSelect control is used when a user has to select an option from a list of options The following table lists some properties of the HtmlSelect control
Property Description
ID Gets or sets a unique identifier to the HtmlSelect control for
reference at the server
Name Gets or sets a unique identifier to the HtmlSelect control for
reference at the client side
Trang 11Property Description
Items Gets the list of items
Multiple Specifies whether multiple items can be selected
SelectedIndex Gets the Index of the selected item
Size Sets the number of visible items in the list
Value Gets the value of the selected item
Properties of the HtmlSelect Control
When an item is selected in the HtmlSelect control, the ServerChange event is generated The following markup illustrates how to implement the HtmlSelect control:
<select Runat="Server" size=4>
Web Server Controls
Web server controls are created on the server and require a runat="server" attribute to work This attribute indicates that the element should be treated as a server control and will be processed at the server However, unlike the HTML server controls, Web server controls do not necessarily map to any existing HTML elements and may represent more complex elements Some of the most commonly used Web server controls are:
TextBox control
Label control
ListBox control
CheckBox and CheckBoxList control
RadioButton and RadioButtonList control
Trang 12The properties of a TextBox control determine the appearance of the TextBox control The following table lists some properties of the TextBox control
Property Description
Text Gets and sets the text in a TextBox control
Height Gets and sets the height of the control
Rows Allows you to set the vertical size of the TextBox control and takes a
value in number of rows If you set both the Height and Rows properties, the Height property takes precedence
Wrap Allows you to set the word wrap behavior in a multi-line TextBox
control The text wraps automatically if the value is set to True
However, if the value is set to False, the user has to press the carriage return key to move to the next line
Properties of the TextBox Control
Trang 13Label Control
The Label control is used to display static text in a Web form that cannot be edited by the user The Text property of the Label control can be set to modify the control’s caption The following table lists some properties of the Label control
Property Description
Text Gets or sets the text of the Label control
Visible Displays or hides the Label control
Properties of the Label Control
ListBox Control
The ListBox control is a collection of list items It allows users to select one or more items from the list The following table lists some properties of the ListBox control
Property Description
Items Represents the collection of list items in the ListBox control
Rows Sets the vertical size of the ListBox control and takes a value in number
of rows If the control contains more than the specified number of items,
a vertical scrollbar is displayed If you set both the Height and Rows properties, the Height property takes precedence
SelectionMode Sets the number of items that can be selected To allow users to select
only one item, you need to set the SelectionMode property to Single
To allow users to select multiple items, you need to set the SelectionMode property to Multiple To select more than one item,
users can hold the CTRL or SHIFT key while selecting the items
Properties of the ListBox Control
The items can be added to a ListBox control by using:
Static item addition method: In this method, the items are added during the design
phase
Dynamic item addition method: In this method, the items are added during run
time
Trang 14Note
CheckBox and CheckBoxList Controls
A check box provides you with independent choices or options that you can select You can add check boxes to a Web form by using either the CheckBox control or the
CheckBoxList control The CheckBox control provides you with a single check box whereas the CheckBoxList control is a collection of several check boxes The choice between using the CheckBox control and using the CheckBoxList control depends on the requirement The CheckBox control provides more control over the layout of the check boxes on a page For instance, you can set the font and color of check boxes individually
or include text between different check boxes The CheckBoxList control is a better choice if you need to add a series of check boxes
The following table lists some properties of the CheckBox and CheckBoxList controls
Text CheckBox control Gets or sets the text of the CheckBox
control
TextAlign CheckBox and
CheckBoxList controls Sets the alignment of the Text property of the CheckBox and the
CheckBoxList controls
Items CheckBoxList control Accesses individual check boxes in
the CheckBoxList control
Properties of the CheckBox and CheckBoxList Controls
Methods for adding items to a CheckBoxList control are similar to the methods used to add items to the ListBox control
RadioButton and RadioButtonList Controls
Radio buttons provide a set of choices or options that you can select You can add radio buttons to a Web form by using either the RadioButton control or the RadioButtonList control The RadioButton control is a single radio button that you can work with whereas the RadioButtonList control is a collection of radio buttons Usually, you use radio
buttons in a group A group of radio buttons provides a set of mutually exclusive options You can select only one radio button in a group
Trang 15You can group a set of radio buttons in the following ways:
Place a set of RadioButton controls in a page and assign them manually to a group by using the GroupName property
Place a RadioButtonList control in a page The radio buttons in this control are grouped by default
After you add a RadioButtonList control, you need to add individual radio buttons You can do so by using the Items property in the same way as you do for the CheckBoxList control Similar to the CheckBox and CheckBoxList controls, the RadioButton control offers more control over the layout of the radio buttons on the page
The following table lists some properties of the RadioButton and RadioButtonList
controls
Text RadioButton control Gets or sets the text of the RadioButton control TextAlign RadioButton and
RadioButtonList controls
Sets the alignment of the Text property of RadioButton and RadioButtonList controls
Items RadioButtonList control Accesses the individual check boxes in the
RadioButtonList control
Properties of the RadioButton and RadioButtonList Controls
The methods for adding items to a RadioButtonList control are similar to the methods for adding items to the ListBox control
Trang 16AdRotator Control
The AdRotator control is used to display flashing banner advertisements on Web pages This control is capable of displaying advertisements randomly AdRotator is one of the rich Web controls available in ASP.NET The following table lists some properties of the AdRotator control
Property Description
AdvertisementFile Sets the path to an XML file that contains a list of banner
advertisements to display The XML file contains multiple <Ad>
elements, one for each advertisement that you want to display
Each <Ad> element contains an <ImageUrl> element that specifies the URL of the image and an <Impressions> element that specifies weights for each image These weights define the relative probability of an image being displayed
KeywordFilter Specifies the filter criteria based on which advertisements of
specific categories will be displayed on a Web page
Target Specifies the name of the Web browser window that will display
the contents of the linked Web page when the AdRotator control
is clicked This parameter can also take any of the following HTML frame-related keywords:
_top: Loads the linked page into the topmost window
_blank: Loads the linked page into a new browser window
_self: Loads the linked page in the same window
_parent: Loads the linked page in the parent window of the window that contains the link
Properties of the AdRotator Control
Trang 17Calendar Control
The Calendar control is used to display a one-month calendar Users can use this control
to view dates or select a specific day, week, or month Calendar is one of the rich web controls available in ASP.NET The following table lists some properties of the Calendar control
Property Description
DayNameFormat Specifies the name format of the days of a week
VisibleDate Specifies the month to be displayed in the Calendar
control This property is updated after the VisibleMonthChanged event is raised
FirstDayOfWeek Specifies the day of the week to be displayed in the first
column of the Calendar control
SelectedDate Represents the date selected in the Calendar control
SelectionMode Specifies whether a user can select a day, a week, or a
month The default value of this property is Day
Properties of the Calendar Control
DropDownList Control
The DropDownList control allows users to select an item from a set of predefined items, where each item is a separate object with its own properties, such as Text, Value, and Selected You can add items to a DropDownList control by using the Items property Unlike the ListBox control, you can select only one item at a time and the list of items remains hidden until the user clicks the drop-down button The following table lists some properties of the DropDownList control
Property Description
Items Represents the collection of list items in the DropDownList control
Width Gets or sets the width of the DropDownList control and takes the
value in pixels
Height Gets or sets the vertical size of the DropDownList control and takes
the value in pixels.
Properties of the DropDownList Control
Trang 18ImageButton Control
The ImageButton control is similar to a button control but unlike the button control, it can also display an image The ImageButton control has a few properties that are identical to the Image control It inherits these properties from the Image control It also has a few properties that are identical to the Button control The following table lists some
properties of the ImageButton control
Property Description
AlternativeText Gets or sets the alternative text that is displayed in the Image control
when a Web browser does not support images
CausesValidation Specifies whether validation will be performed when the Button
control is clicked If the value is False, the form submitted by the button is not validated The default value of this property is True CommandArgument Passes a value to the Command event along with the associated
command name when the button is clicked
ImageAlign Gets or sets the alignment of the image The possible values for this
property are Top, Left, Right, Middle, Bottom, AbsBottom, AbsMiddle, Baseline, Middle, NotSet, and TextTop
ImageURL Specifies the URL of the image to be displayed
CommandName Gets or sets the command name associated with the Button control
that is passed to the Command event
Properties of the ImageButton Control
Trang 19The following table describes how these buttons appear on a Web page
Control Description
Button Rendered as a standard command button that is rendered as an
HTML input element
LinkButton Rendered as a hyperlink on a Web page It contains client-side
script that causes the form to be posted back to the server
ImageButton Rendered in the form of a graphic button It is used for presenting
a rich button appearance
Types of Button Control
The following table lists some common properties of all the three Button controls
ToolTip Gets or sets the text displayed when the mouse pointer hovers over
the button control
Common Properties of Button Controls
Wizard Control
A wizard is a group of forms used to accomplish a particular task ASP.NET provides a Wizard control that is used to enable a user to perform a task step-by-step or to collect user input related to the task A Wizard control contains a series of forms that describe the whole task It provides an easy mechanism that allows you to build steps, add a new step,
or reorder the steps
With the help of the Wizard control, a user can move between steps, which create a simple user experience for performing a task As a developer, you need not worry about preserving data across the Web pages as the control maintains the state while a user performs the various steps of the wizard
Trang 20The following table lists some properties of the Wizard control
Property Description
ID Gets or sets the unique identifier assigned to the Wizard
control
WizardSteps Gets a collection of all the WizardStepBase objects that
are defined for the control
EnableViewState Gets or sets a value indicating whether the Wizard control
persists its view state, and the view state of any child controls it contains
Enabled Gets or sets a value indicating whether the Wizard control
is enabled
ToolTip Gets or sets the text displayed when the mouse pointer
hovers over the Wizard control
Properties of the Wizard Control
MultiView Control
A Multiview control is a set of View controls These View controls, in turn, contain child controls such as buttons and textboxes A Web application dynamically displays a View control to a user based on certain criteria such as user identity, preferences, or information passed in a query string parameter It is used to present alternate views of information
The following table lists some properties of the MultiView control
is rendered as UI on the page
Properties of the MultiView Control