Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Objectives
In this chapter, you will learn to:
Use ASP.NET Web Server controls
Create custom controls
Chapter 2
Note
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.
NIIT
Note
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.
NIIT
5.
6.
7.
8.
9.
PreRendering: The control is updated with the changes made in it by the user. This
is done in preparation for rendering.
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.
Rendering: The server creates the corresponding HTML tag for the control.
Disposing: All cleanup tasks, such as closing files and database connections opened
by the control are performed.
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.
Note
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.
Validation controls
HtmlAnchor control
HtmlInputText control
HtmlInputCheckBox control
HtmlInputRadioButton control
HtmlSelect control
NIIT
HtmlAnchor 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
Href
Gets or sets the URL of the page to which the control is linked.
Name
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 href
attribute. 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.
NIIT
HtmlInputText 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.
Property
Description
ID
Type
Name
Size
MaxLength
Gets or sets the value for the maximum characters that can be entered in
the textbox.
Value
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 txtName1
can 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.
NIIT
Description
ID
Name
Checked
Value
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">
NIIT
Description
ID
Checked
Gets or sets the status of the radio button. This property will
return true if the radio button is selected.
Name
Value
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">
Titanic
Description
ID
Name
NIIT
Property
Description
Items
Multiple
SelectedIndex
Size
Value
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>
<option>Titanic</option>
<option>The Lords of the Ring</option>
<option>Matrix Reloaded</option>
<option>Harry Potter</option>
</select>
The preceding markup creates a list box containing four movie names as list items. Out of
these movie names only one can be selected at a time.
TextBox control
Label control
ListBox control
AdRotator control
Calendar control
DropDownList control
ImageButton control
Button control
NIIT
Wizard control
MultiView control
HyperLink control
FileUpload control
XML control
Substitution control
TextBox Control
The TextBox control is used to obtain information, such as text, numbers, and dates from
users in a Web form. You can set a TextBox control as single-line, password, or multi-line
TextBox control. By default, a TextBox control is single-line that allows users to type
characters in a single line only. A password TextBox control is similar to the single-line
TextBox control, but masks the characters typed by users and displays them as asterisks
(*). A multi-line TextBox displays multiple lines and allows text wrapping.
The 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
Height
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
NIIT
Label 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 controls caption.
The following table lists some properties of the Label control.
Property
Description
Text
Visible
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
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
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.
NIIT
Available with
Description
Text
CheckBox control
TextAlign
CheckBox and
CheckBoxList controls
Items
CheckBoxList control
Note
Methods for adding items to a CheckBoxList control are similar to the methods used to
add items to the ListBox control.
NIIT
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.
Property
Available with
Description
Text
RadioButton control
TextAlign
RadioButton and
RadioButtonList
controls
Items
RadioButtonList control
Note
The methods for adding items to a RadioButtonList control are similar to the methods
for adding items to the ListBox control.
NIIT
AdRotator 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
KeywordFilter
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
NIIT
Calendar 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
VisibleDate
FirstDayOfWeek
SelectedDate
SelectionMode
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
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
NIIT
ImageButton 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
CommandArgument
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
CommandName
Gets or sets the command name associated with the Button control
that is passed to the Command event.
Properties of the ImageButton Control
Button Control
The Button control is generally used to submit the data that is entered by a user as an
input in a Web application. When the user clicks a button control on a Web page, the page
is posted back to the Web server, and the click event is triggered. ASP.NET provides
three types of button controls; Button, LinkButton, and ImageButton.
NIIT
The following table describes how these buttons appear on a Web page.
Control
Description
Button
LinkButton
ImageButton
The following table lists some common properties of all the three Button controls.
Property
Description
ID
Text
PostBackURL
Gets or sets the URL of the Web page to which the data is posted.
Enabled
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.
NIIT
Description
ID
WizardSteps
EnableViewState
Enabled
ToolTip
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.
Property
Description
ID
Views
Visible
NIIT
HyperLink Control
A HyperLink control is used to link all the Web pages in a Web application. By using a
HyperLink control, a user can easily move between the Web pages. It is rendered as a
clickable text or an image on a Web page. A HyperLink control does not raise an event in
the server code when a user clicks it. Instead, it simply performs navigation. In other
words, it directs the user to another Web page. The following table lists some properties
of the HyperLink control.
Property
Description
Text
ImageUrl
Creates a graphical link when you set the URL property of the
control to a .gif, .jpg, or other Web graphic file.
NavigateUrl
Target
FileUpload Control
The FileUpload control enables users to send a file from their computer to the server. It is
useful for allowing users to upload various types of files such as pictures, text files, or
other files. The files that are to be uploaded are submitted to the server as part of the
browser request during postback.
The FileUpload control displays a textbox to type the name of the file that is to be
uploaded on the server. It also displays a Browse button that that can be used to browse
for the file. The following table lists some properties of the FileUpload control.
Property
Description
Filename
HasFile
NIIT
XML Control
The XML control is used to write the output of an XML document on a Web page. The
XML output appears at the location of the control on the Web page. The following table
lists some properties of the XML control.
Property
Description
Document
DocumentContent
DocumentSource
Substitution Control
The Substitution control is used on the Web pages that are configured to be cached. It
allows you to create areas on the page that can be updated dynamically and integrated into
the cached page.
When a page is cached, the entire output of the page is cached. However, there may be
situations wherein you need to cache a page but want to update the selected portions of
the page on each request. For updating the selected portions in a cached page, you can
place the Substitution control in the cached page and insert dynamic content into the
Substitution control. The following table lists some properties of the Substitution control.
Property
Description
MethodName
Site
Validation Controls
Validation is the process of checking something against a certain criterion. There are
various situations where validation is required. One such situation is when a user fills out
a form for which the minimum age required is 18 years. In such a situation, when the user
submits the form, the age must be validated against the criterion. If the criterion is
2.22 Working with Controls
NIIT
satisfied, the form is accepted, otherwise it is rejected. Such type of validation can be
implemented on a website by using the ASP.NET validation controls.
ASP.NET provides the following validation controls that can be attached to input controls
to validate the values that are entered by the user:
RequiredFieldValidator control
RegularExpressionValidator control
CompareValidator control
RangeValidator control
ValidationSummary control
CustomValidator control
RequiredFieldValidator Control
The RequiredFieldValidator control is used to check whether a server control, added to a
Web form, has a value or not. For example, you can use this validation control to check
whether a user has entered any value in the password textbox.
The following table lists some properties of the RequiredFieldValidator control.
Property
Description
ControlToValidate
ErrorMessage
Text
RegularExpressionValidator Control
The RegularExpressionValidator control is used to check whether the server control added
to a Web form matches with a specific regular expression or not. The regular expression
can be the format of a telephone number or an e-mail address.
NIIT
Description
ControlToValidate
ErrorMessage
ValidationExpression
CompareValidator Control
The CompareValidator control is used to compare the entered value with another value.
The other value can be a number or a value entered into another control. The following
table lists some properties of the CompareValidator control.
Property
Description
ControlToCompare
ControlToValidate
ErrorMessage
ValueToCompare
RangeValidator Control
The RangeValidator control is used to check whether the value of a particular Web form
field is within the range specified by the RangeValidator controls MinimumValue and the
MaximumValue properties. The MinimumValue and MaximumValue properties can contain
dates, numbers, currency amounts, or strings.
NIIT
Description
ControlToValidate
ErrorMessage
MaximumValue
MinimumValue
ValidationSummary Control
The ValidationSummary control is used to summarize all errors and display the error list
at a location specified by the user on the Web page. The following table lists some
properties of the ValidationSummary control.
Property
Description
HeadText
ShowMessageBox
ShowSummary
NIIT
CustomValidator Control
The CustomValidator control is used to perform user-defined validations that cannot be
performed by standard validation controls. The following table lists some properties of the
CustomValidator control.
Property
Description
ControlToValidate
ErrorMessage
Sender Object: This is the first argument and is an instance of System.Object class.
This represents the control that raised the event.
Postback events: In postback events, a Web page is sent back to the server for
processing. When a user clicks a button, the click event of the button causes a Web
page to be posted back to the server. When a Web page is posted back to the server,
the server processes the page and sends it back to the user.
2.26 Working with Controls
NIIT
Event Handlers
When an event is raised, the corresponding event handler is searched and the code written
in the event handler is executed. If you want your application to perform some action
when an event is raised, you need to add an event handler for that event.
The various approaches that can be used to work with event handlers include:
NIIT
The AutoEventWireup attribute can have two values, true or false. When the value is
set to true, the ASP.NET runtime does not require events to specify event handlers, such
as Page_Load and Page_Init. This means that in Visual C#, you do not have to initialize
and create the delegate structures. However, when the value is set to false, the events
need to specify event handlers explicitly.
Creating Centralized Event-Handlers
There are situations when you want to associate the same event handler with different
controls. Such situations can be handled by using a centralized event handler. A
centralized event handler eliminates the need for declaring separate event handlers for
different ASP.NET objects. You can create one centralized event handler that can perform
appropriate action at runtime.
When you create a single event handler to respond to multiple events that should trigger
different actions, you need to determine which event invoked the event handler. To
determine which control caused the event, you need to perform the following steps:
1. Declare a variable in the event handler with a type that matches the control that
raised the event.
2. Assign the sender argument of the event handler to the variable, casting it to the
appropriate type.
3. Examine the ID property of the variable to determine which object raised the event.
Consider a Web page containing the following markup:
<asp:Button ID="Button1" runat="server" Text="Button1"
onclick="Button1_Click" />
<asp:Button ID="Button2" runat="server" Text="Button2"
onclick="Button1_Click" />
NIIT
In the preceding example, the event handler Button1_Click is associated with both the
button controls. You need to write the event handler in such a manner that it will
determine which control has caused the event. The following code snippet illustrates how
to write such an event handler:
protected void Button1_Click(object sender, EventArgs e)
{
Button mybtn = (Button)sender;
switch (mybtn.ID)
{
case "Button1": Response.write("You have clicked Button
1");
break;
case "Button2": Response.write ("You have clicked Button
2");
break;
}
}
The preceding code works well to define a centralized event handler for the Click event
of the Button control. However, if you need to create a centralized event handler for the
Command event of two button controls, the preceding code will not work because the
Command event passes a different set of arguments to its event handler.
Consider a Web page containing the following markup:
<asp:Button ID="Button1" runat="server" Text="Button1"
CommandName=Prev onCommand="Button1_Command" />
<asp:Button ID="Button2" runat="server" Text="Button2"
CommandName=Next onCommand="Button1_Command" />
In the preceding example, the event handler Button1_Command is associated with both the
button controls. You need to write the event handler in such a manner that it will
determine which control has caused the event. The following code snippet illustrates how
to write such an event handler:
protected void Button1_Command(object sender, CommandEventArgs e)
{
switch (e.CommandName)
{
case "Prev": Response.Write("You clicked the Prev
button");
break;
case "Next": Response.Write("You clicked the Next
button");
break;
}
}
NIIT
PlaceHolder
Panel
PlaceHolder
A PlaceHolder control is used as a container that is not visible in a Web application. It is
added to a Web page to hold other controls on the page. The PlaceHolder control reserves
a place in the structure of the Web page for other controls that are added dynamically. The
following markup adds a PlaceHolder control to a Web page:
<asp:PlaceHolder id="PlaceHolder1" runat="server"/>
The following code snippet shows how to add a Button control and a literal in a
PlaceHolder control:
void Page_Load(object sender, EventArgs e)
{
//creates an instance of a button control.
Button Button1 = new Button();
Button1.Text = "Button 1";
// Adds the button control in a PlaceHolder control.
PlaceHolder1.Controls.Add(Button1);
// creates an instance of a literal control.
Literal Literal1 = new Literal();
Literal1.Text = " Dynamically loaded controls";
// Adds the literal control in a PlaceHolder control.
PlaceHolder1.Controls.Add(Literal1);
NIIT
Panel
A Panel control is also used as a container for other controls. The only difference between
a PlaceHolder and a Panel control is that a Panel control renders div tag around all the
child controls in the panel where as a PlaceHolder will only render its child controls. This
makes panels useful when you want to apply a css class to a container. The following
code snippet shows how to add a Label control to a Panel control:
//Creating an instance of a Label control
Label TestLabel = new Label();
TestLabel.Text = "testlabel";
//Adding the Label control to a Panel control
Panel1.Controls.Add(TestLabel);
NIIT
NIIT
Note
You can navigate to a generic handler by using the Respose.redirect() method.
For example, you want that on clicking the Show Picture button on the default.aspx
page, the generic handler MyHandler.ashx is displayed in the browser. For this, you
need to write the following code snippet in the event handler for the Click event of the
button:
Response.Write(MyHandler.ashx);
NIIT
A user control contains the @Control directive instead of the @Page directive.
User controls cannot run as stand-alone files. They need to be added to ASP.NET
pages to make them work.
User controls do not have <html>, <body>, or <form> elements in them. These
elements must be present on the Web page that is hosting these controls.
A Web user control on a Web page must be registered before it is used. You can register a
Web user control by using the @Register directive as illustrated in the following markup:
<%@Register TagPrefix="ABC" TagName="Header" Src="mycontrol.ascx" %>
NIIT
TagPrefix: Specifies the alias to associate with the namespace of the user control.
TagName: Specifies the alias to associate with the class of the user control.
Src: Specifies the virtual path of the file containing the user control.
After registering the control, you can include it on the page by writing the markup as
shown in the following example:
<ABC:Header ID=mycontrol1 runat="Server"/>
Controls that combine two or more existing controls: This type of control is
known as a composite control and can be created by defining a class that derives
from the System.Web.UI.Control or System.Web.UI.WebControl class and
overrides the CreateChildControls method of the base class. In addition, the class
can expose public properties that will be accessible to the pages that use this control.
Controls that extend the functionality of an existing control: This type of control
is created when an existing control meets most of your requirements but lacks some
features. In such a situation, you can customize the existing control by defining a
class that derives from the class corresponding to the existing control. You can then
add new properties and override existing methods and events of the base class to
modify the functionality of the control.
NIIT
Controls that are not similar to any existing control: This type of control is
created when none of the existing controls meets your requirement. In such a case,
you can create a custom control by deriving from the System.Web.UI.Control or
System.Web.UI.WebControl class, adding public properties to this class, and
overriding existing methods of the base class.
Task 2.5: Creating and Using a Composite Control
Task 2.6: Creating and Using a Web Custom Control that Extends
the Functionality of an Existing Control
Task 2.7: Creating and Using a Web Custom Control that is Not
Similar to any Existing Control
NIIT
5.
For each data item, write code in the Page_Init event handler of the user control to:
a. Create an instance of the naming container class.
b. Create an instance of the template in the naming container.
c. Add the naming container instance to the Controls property of the PlaceHolder
server control.
Note
Repeater, DataList, and GridView Web server controls are the examples of built-in
Templated controls. These controls will be discussed in detail later in the course.
NIIT
Practice Questions
1.
2.
During which of the following phase, a control is updated with the changes made to
it by the user?
a. PreRendering
b. Loading
c. Rendering
d. Disposing
Which of the following properties gets or sets the value of the tooltip attribute of the
<a> tag?
a.
b.
c.
d.
Name
Target
Title
Href
3.
Which of the following Web server controls is used to display flashing banner
advertisements on Web pages?
a. ImageButton control
b. Check Box control
c. MultiView control
d. AdRotator control
4.
Which of the following validation controls is used to check whether a server control
added to a Web form has a value or not?
a. RequiredFieldValidator
b. RegularExpressionValidator
c. CompareValidator
d. RangeValidator
5.
Which of the following HTML-frame related keyword loads the linked page in a new
browser window?
a. _top
b. _blank
c. _parent
d. _self
NIIT
Summary
In this chapter, you learned that:
Server controls are the fundamental building blocks that are specifically designed to
work with Web forms in an ASP.NET application.
The sequence in which a server control is processed when the page is requested for
the first time is:
a. Initializing
b. Loading
c. PreRendering
d. Saving
e. Rendering
f. Disposing
g. Unloading
The sequence in which a server control is processed when the Web page is posted
back to the Web browser is:
a. Initializing
b. Loading view state
c. Loading control instance
d. Loading the postback data
e. PreRendering
f. Saving
g. Rendering
h. Disposing
i. Unloading
The various types of server controls provided by ASP.NET can be classified into the
following categories:
z
HTML server controls
z
Web server controls
z
Validation controls
z
User controls
An event is a message that contains details about the user action, such as the cause of
the event and the control on which the event occurred.
NIIT
NIIT