08 asp.net chapter 02

40
   Working with Controls    C    h   a   p    t   e   r    2  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 requiremen ts. 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

Upload: san-toso

Post on 04-Oct-2015

217 views

Category:

Documents


0 download

DESCRIPTION

hjjjj fdgdyt arrfgt

TRANSCRIPT

  • Working with Controls Cha

    pter

    2

    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

  • NIIT Working with Controls 2.3

    Note

    In the earlier days of Web development, the programmers had to use HTML controls to design a Web application because there were no other controls available. The HTML controls do not provide any built-in methods and events. Programmers had to manually write the methods and events by using client-side scripts to create a dynamic Web page. This is a time-consuming process. In addition, it is insecure because the client-side scripts are visible to the users when they view the source for the Web page.

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

  • 2.4 Working with Controls 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.

    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

  • NIIT Working with Controls 2.5

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

  • 2.6 Working with Controls NIIT

    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.

    ASP.NET provides various types of server controls. These controls can be classified into the following categories: HTML server controls Web server controls Validation controls

    HTML Server Controls

    In traditional websites, HTML controls were used to enable users to interact with the website. Developers had to write the methods and events for these controls manually to provide functionality to them. This was a very tedious task. In addition, these controls were processed by the Web browser that is on the client-side, which does not provide the functionality for validating the user input or managing the state.

    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: HtmlAnchor control HtmlInputText control HtmlInputCheckBox control HtmlInputRadioButton control HtmlSelect control

    Types of Server Controls

  • NIIT Working with Controls 2.7

    HtmlAnchor Control

    The HtmlAnchor control works like the HTML 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 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:

    Click here Click here

    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.

  • 2.8 Working with Controls NIIT

    HtmlInputText Control

    The HtmlInputText control works like the HTML 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 Gets or sets a unique identifier to the HtmlInputText control for reference at the server.

    Type Sets Type="Text" or Type ="Password" to specify the mode of work.

    Name Gets or sets a unique identifier to the HtmlInputText control for reference 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:

    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 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 Working with Controls 2.9

    The 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:

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

    HTMLInputRadioButton Control

    The HtmlInputRadioButton control works as the HTML tag but runs on the server. You can use the HtmlInputRadioButton control to implement multiple-choice questions, where a user can select only one option.

  • 2.10 Working with Controls NIIT

    The 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:

    Titanic

    The preceding markup uses an HtmlInputRadioButton control named MyRadioButton, as specified by the id attribute. The MyRadioButton HtmlInputRadioButton control belongs to a group GroupRadio as specified by the name attribute. When MyRadioButton is selected or cleared, the FunctionRadio method attached to its ServerChange event is invoked. The OnServerChange attribute is used to attach an event handler to the ServerChange event.

    HtmlSelect Control

    The HtmlSelect control is same as the HTML 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.

  • NIIT Working with Controls 2.11

    Property 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:

    Titanic The Lords of the Ring Matrix Reloaded Harry Potter

    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.

    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 AdRotator control Calendar control DropDownList control ImageButton control Button control

  • 2.12 Working with Controls 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 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

  • NIIT Working with Controls 2.13

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

  • 2.14 Working with Controls NIIT

    Note

    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.

    Property Available with Description

    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.

  • NIIT Working with Controls 2.15

    Note

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

    Property Available with Description

    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.

  • 2.16 Working with Controls 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 Sets the path to an XML file that contains a list of banner advertisements to display. The XML file contains multiple elements, one for each advertisement that you want to display. Each element contains an element that specifies the URL of the image and an 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

  • NIIT Working with Controls 2.17

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

  • 2.18 Working with Controls 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 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

    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 Working with Controls 2.19

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

    Property Description

    ID Gets or sets the unique identifier assigned to the button control.

    Text Gets or sets the text that is displayed on the Button control.

    PostBackURL Gets or sets the URL of the Web page to which the data is posted.

    Enabled Gets or sets a value indicating whether the button control is 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.

  • 2.20 Working with Controls NIIT

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

    Property Description

    ID Gets or sets the unique identifier assigned to the MultiView control.

    Views Gets the collection of View controls in the MultiView control.

    Visible Gets or sets a value that indicates whether a MultiView control is rendered as UI on the page.

    Properties of the MultiView Control

  • NIIT Working with Controls 2.21

    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 Specifies the text displayed as a hyperlink on a Web browser.

    ImageUrl Creates a graphical link when you set the URL property of the control to a .gif, .jpg, or other Web graphic file.

    NavigateUrl Specifies the URL of the page to which you want to link.

    Target Indicates the ID of a target window or frame in which you want to display as a linked page.

    Properties of the HyperLink Control

    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 Gets the name of the file on the client computer to be uploaded.

    HasFile Gets a value that indicates whether the control contains a file.

    Properties of the FileUpload Control

  • 2.22 Working with Controls 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 Gets or sets the XML document to be displayed.

    DocumentContent Sets a string that contains the XML document to display.

    DocumentSource Gets or sets the path of the XML document whose output is to be displayed.

    Properties of the XML Control

    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 Gets or sets the name of the method to be invoked when the Substitution control executes.

    Site Gets information about the container that hosts the current control when rendered on a design surface.

    Properties of the Substitution Control

    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

  • NIIT Working with Controls 2.23

    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 Specifies the ID of the control to be validated.

    ErrorMessage Specifies the error message to be displayed when the validation condition fails.

    Text Specifies the error message displayed by the control.

    Properties of the RequiredFieldValidator Control

    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.

  • 2.24 Working with Controls NIIT

    The following table lists some properties of the RegularExpressionValidator control.

    Properties of the RegularExpressionValidator Control

    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 Specifies the ID of the control that will be used to compare values.

    ControlToValidate Specifies the ID of the control to be validated.

    ErrorMessage Specifies the error message to be displayed when the validation condition fails.

    ValueToCompare Specifies the ID of the control to be compared.

    Properties of the CompareValidator Control

    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.

    Property Description

    ControlToValidate Specifies the ID of the control to be validated.

    ErrorMessage Specifies the error message to be displayed when the validation condition fails.

    ValidationExpression Specifies the regular expression, when performing validation.

  • NIIT Working with Controls 2.25

    The following table lists some properties of the RangeValidator control.

    Property Description

    ControlToValidate Specifies the ID of the control to be validated.

    ErrorMessage Specifies the error message to be displayed when the validation condition fails.

    MaximumValue Specifies the maximum value.

    MinimumValue Specifies the minimum value.

    Properties of the RangeValidator Control

    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 Gets or sets the text to be displayed at the top of the summary.

    ShowMessageBox Displays the error message in a pop-up message box when the value of this property is True.

    ShowSummary Enables or disables the summary of error messages.

    Properties of the ValidationSummary Control

  • 2.26 Working with Controls 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 Specifies the ID of the control that is to be validated.

    ErrorMessage Specifies the error message to be displayed when validation condition fails.

    Properties of the CustomValidator Control

    Every server control has some events associated with it. 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.

    When a user interacts with a server control, its corresponding event is invoked and the code written on the event is executed. For example, when a user clicks a button, the Click event of the button control is invoked and the code written on the event is executed.

    Most of the ASP.NET events pass the following two arguments: Sender Object: This is the first argument and is an instance of System.Object class.

    This represents the control that raised the event. Event object: This is an instance of System.EventArgs class. This contains

    information about the event that is generated.

    ASP.NET Server Control Event Model

    In traditional client-based Web applications, the events are raised and processed on the client machine. However, in ASP.NET, events associated with the server controls originate on the client but the processing of the events happens only on the server. ASP.NET supports two types of events: 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.

    Server Control Events

  • NIIT Working with Controls 2.27

    Nonpostback events: In nonpostback events, a Web page does not immediately cause a postback. For example, change events in HTML server controls and Web server controls, such as the TextBox control, are captured but do not immediately cause a post. These events are cached by the control until the next time a post occurs. When a post occurs, the page is processed on the server and all the pending events are raised and processed.

    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: Using default events Using non-default events Using the AutoEventWireup capabilities of a Web form Creating centralized event-handlers

    Using Default Events

    Every control exposes an event that is designated as the default event. A default event is an event that is most commonly associated with a control. For example, the Click event is the default event of a Button control. Default events are handled by a default event handler.

    Task 2.1: Creating a Default Event Handler

    Using Non-Default Events

    In addition to the default event, each control exposes other events, called non-default events. For example, the Command event is a non-default event of a Button control. Non-default events are handled by non-default event handlers.

    Task 2.2: Creating a Non-Default Event Handler

  • 2.28 Working with Controls NIIT

    Using the AutoEventWireup Capabilities of a Web Form

    ASP.NET provides the event wire-up capability to a Web form using which events can be automatically associated with event-handling procedures having well-defined names and signatures. Event wire-ups determine the procedures that need to be called when objects raise events. To enable the event wire-up capability of a Web form, you need to set the AutoEventWireUp attribute of the .aspx page to true. By default, the AutoEventWireUp attribute of the .aspx pages is set to true, as shown in the following markup:

    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:

  • NIIT Working with Controls 2.29

    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:

    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; } }

  • 2.30 Working with Controls NIIT

    There are situations where you need to add controls dynamically to a Web page. Consider a situation where you are designing a registration form for an insurance company. The form has a section where the persons seeking insurance have to enter the name and age of their family members. The number of family members varies from user to user. Therefore, you cannot add the textboxes for entering the name and age at the design time. Such a situation can be handled by adding the controls at run time. Adding controls to a Web page at run time makes a website flexible, interactive, and user-friendly.

    When adding a control dynamically to a Web page, you need to place them in a container so as to make the Web page well-structured. Two controls that act as containers when adding controls dynamically are: 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:

    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); }

    Loading Controls Dynamically

  • NIIT Working with Controls 2.31

    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);

    An event handler for a control is usually created at design time. However, it can also be created dynamically at run time for the controls that are created dynamically. For example, to create a Button control dynamically and associate an event handler to it at run time, you need to write the following code in the .cs file of a Web page:

    protected void Page_Load(object sender, EventArgs e) { Button btn=new Button(); btn.Text = "Click Me"; form1.Controls.Add(btn);//Adding button to the form btn.Click += new EventHandler(btn_Click); } protected void btn_Click(object sender, EventArgs e) { Response.Write("Hello"); }

    Activity 2.1: Creating a Web Application by Using ASP.NET

    Adding Event Handlers Dynamically

  • 2.32 Working with Controls NIIT

    The .aspx files are the default HTTP handler for all ASP.NET pages. However, there may be situations wherein you want that instead of .aspx files the request is handled by generic handlers. For example, you have created the ProductDetails page in which you are displaying the details of a product. This page has a button control, clicking on which a page having the image of the product is displayed. Instead of using a Web page to display an image, you can use a generic handler.

    A generic handler can be used when you want to display the output of a text file, XML file, or display an image. This is because a generic handler uses fewer resources as compared to Web pages. Therefore, it enhances the performance of your Web application.

    The generic handler provides a class that implements the IHttpHandler interface. The class provides the ProcessRequest method and the IsReusable property. The processRequest method is responsible for processing individual HTTP requests. This method is used to write the code that produces the output for the handler. The IsReusable property specifies whether the IHttpHandlerFactory object can put the handler in a pool and reuse it to increase performance. The IHttpHandlerFactory object is the object that calls the appropriate handler.

    Consider the following example: using System; using System.Web; public class SimpleHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { HttpResponse r = context.Response; //Create and initialize an //HttpResponse object r.ContentType = "image/png"; //Set the Content type for the //HttpResponse object //Write the image r.WriteFile(@"~\images\4.JPG"); } public bool IsReusable { get {return true;} } }

    In the preceding example, the generic handler is used to display an image.

    Implementing Generic Handler

  • NIIT Working with Controls 2.33

    Note

    Task 2.3: Adding a Generic Handler to a Website

    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);

  • 2.34 Working with Controls NIIT

    Developers use various Web server controls to enable users to interact with the Web pages. There might be a situation where you need some functionality that is not provided by the in-built Web server controls or you might want to reuse the same set of controls, which you have added to one Web page, on another Web page. For example, you have created a customized Login page with two labels, two textboxes, and one button to enable the user to log on to a website. You want to reuse the same Login page in all other Web applications. In such a case, you can create a custom control with the required customizations and then reuse it in as many Web applications as you want.

    Custom controls are controls that are created by combining two or more controls and can be reused in multiple Web applications. You can create the following types of custom controls: Web user controls Web custom controls Templated user controls

    Web user controls are containers that can be created by combining one or more Web server controls. After creating a Web user control, you can treat it as a unit and define properties and methods for it. Web user controls are similar to ASP.NET Web pages in the context that they contain both a user interface page and code.

    A Web user control is created in the same way as you create an ASP.NET page. However, it differs from an ASP.NET Web page in the following ways: The file name extension of a user control is .ascx. 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 , , or 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:

    Creating Custom Controls

    Web User Controls

  • NIIT Working with Controls 2.35

    The preceding markup contains the following three attributes: 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:

    Task 2.4: Creating and Using a Web User Control

    There may be situations where you need a new control with properties that are not provided by any of the existing server controls. In such situations, you cannot use a Web user control because a Web user control is created by combining one or more server controls. Such situations can be handled by writing code to create a new control. These controls are known as Web custom controls.

    Web custom controls provide an approach to reuse logic in an ASP.NET application. Web custom controls are written as classes. Web custom controls are written entirely by using managed code and have no markup files. These controls are compiled into an assembly before the deployment of the application.

    Web custom controls are of the following three types: 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.

    Web Custom Controls

  • 2.36 Working with Controls 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

    A templated user control allows developers to modify the layout of its user interface by defining their own templates. Templated user controls allow the separation of control data from its presentation. They do not have a user interface; instead they simply implement a naming container and include a class whose properties and methods are accessible to the host page. The user interface of the control is defined at the time of designing the Web page on which the templated control is to be used.

    To create a templated user control, you need to perform the following steps: 1. Add an ASP.NET PlaceHolder control in the .ascx file of the user control to specify

    the place where you want the template to appear. 2. Implement a property of type ITemplate in the code of the user control. 3. Define a server control class that implements the INamingContainer interface as a

    container in which an instance of the template can be created. This class is called the templates naming container.

    4. Apply the TemplateContainer attribute to the property that implements ITemplate and pass the type of the templates naming container as the argument to the attributes constructor.

    Templated User Controls

  • NIIT Working with Controls 2.37

    Note

    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.

    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.

    Task 2.8: Creating and Using a Templated User Control

  • 2.38 Working with Controls NIIT

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

    2. Which of the following properties gets or sets the value of the tooltip attribute of the tag? a. Name b. Target c. Title d. 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

    Practice Questions

  • NIIT Working with Controls 2.39

    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. Server controls provide:

    z Automatic state maintenance. z Browser independent rendering. z Easily programmable model.

    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.

    Summary

  • 2.40 Working with Controls NIIT

    The two arguments passed by all events in ASP.NET are: z Sender Object z Event object

    The two types of events in ASP.NET server control event model are: z Postback events z Nonpostback events

    The two controls that act as container when adding controls dynamically are: z PlaceHolder z Panel

    The two types of custom controls are: z Web user controls z Web custom controls z Template user controls