best tutorial of c#

116
1) DropDownList Web Server Control Overview The DropDownList Web server control enables users to select a single item from a predefined drop-down list. Features You can use the DropDownList control to: Use data-binding to specify the list of items to display. Determine which item is selected. Specify the selected item programmatically. Background The DropDownList Web server control enables users to select an item from a predefined list. It differs from the ListBox Web server control in that the list of items remains hidden until users click the drop-down button. In addition, the DropDownList control does not support multi-selection mode. Modifying the Appearance of the DropDownList Control You can control the look of the DropDownList control by setting its height and width in pixels. Some browsers do not support setting the height and width in pixels and will use the row-count setting instead. You cannot specify the number of items that are displayed in the list when users click the drop-down button. The length of the displayed list is determined by the browser. As with other Web server controls, you can use style objects to specify the appearance of the DropDownList control. For details, see ASP.NET Web Server Controls and CSS Styles. List Items

Upload: dhwani1621

Post on 08-Nov-2014

43 views

Category:

Documents


0 download

DESCRIPTION

its really a good document to get an idea about C# ...must read ..

TRANSCRIPT

Page 1: Best Tutorial of c#

1) DropDownList Web Server Control Overview The DropDownList Web server control enables users to select a single item from a predefined drop-down list.

Features

You can use the DropDownList control to:

Use data-binding to specify the list of items to display. Determine which item is selected. Specify the selected item programmatically.

Background

The DropDownList Web server control enables users to select an item from a predefined list. It differs from the ListBox Web server control in that the list of items remains hidden until users click the drop-down button. In addition, the DropDownList control does not support multi-selection mode.

Modifying the Appearance of the DropDownList Control

You can control the look of the DropDownList control by setting its height and width in pixels. Some browsers do not support setting the height and width in pixels and will use the row-count setting instead.

You cannot specify the number of items that are displayed in the list when users click the drop-down button. The length of the displayed list is determined by the browser.

As with other Web server controls, you can use style objects to specify the appearance of the DropDownList control. For details, see ASP.NET Web Server Controls and CSS Styles.

List Items

The DropDownList control is actually a container for the list items, which are of type ListItem. Each ListItem object is a separate object with its own properties. These properties are described in the following table.

Property Description

Text Specifies the text that is displayed in the list.

Value Contains the value that is associated with an item. Setting this property enables you to associate a value with a

specific item without displaying it. For example, you can set the Text property to the name of a color and the

 Value property to its hexadecimal representation.

Page 2: Best Tutorial of c#

Selected Indicates whether the item is currently selected.

To work with list items programmatically, use the Items collection of the DropDownList control. The Items collection is a standard collection, and you can add item objects to it, delete items, clear the collection, and so on.

The currently selected item is available in the DropDownList control's SelectedItem property.

Binding Data to the Control

You can use a DropDownList Web server control to list options that are made available to the page using a data source control. Each item in the DropDownList control corresponds to an item in the data source, typically an individual data record.

The control displays one field from the source. Optionally, you can bind the control to a second field to set the value of an item, which is not displayed.

As with other Web server controls, you can bind any control properties to data, such as the color or size of the control. For details, see How to: Populate List Web Server Controls from a Data Source.

DropDownList Events

The DropDownList control raises the SelectedIndexChanged event when users select an item. By default, this event does not cause the page to be posted to the server. However, you can cause the control to force an immediate post by setting the AutoPostBack property to true.

NoteThe auto-postback capability requires that the browser support ECMAScript (JScript, or JavaScript) and that scripting be enabled on the user's browser.

Code Examples

How to: Add DropDownList Web Server Controls to a Web Forms Page

How to: Determine the Selection in List Web Server Controls

How to: Respond to Changes in List Web Server Controls

How to: Add Items in List Web Server Controls

How to: Populate List Web Server Controls from a Data Source

How to: Set the Selection in List Web Server Controls

Page 3: Best Tutorial of c#

Class Reference

The following table lists the classes that relate to the DropDownList control.

Member Description

DropDownList The main class for the control.

ListItem The class that represents each item in the drop-down list.

1) AdRotator Web Server Control Overview

The AdRotator Web server control can be used to display graphics that are linked to other pages. The list of graphics to be displayed and the associated target links is maintained in a data source such as an XML file or database.

The AdRotator Web server control provides a way to display advertisements (ads) on your ASP.NET Web pages. The control displays a .gif file or other graphic image that you provide. When users click the ad, they are redirected to a target URL that you have specified. The control automatically reads advertisement information, such as the graphic file name and the target URL, from a list of ads that you provide using a data source, which is usually an XML file or a database table.

The AdRotator control selects ads randomly, changing the displayed ad each time the page is refreshed. Ads can be weighted to control the priority level of banners, making it possible to have certain ads display more often than others. You can also write custom logic that cycles through the ads.

Background

The AdRotator Web server control can be used to display ad graphics such as a .gif or similar image. The user can then be redirected to a target URL. The graphic and target URL can be provided from a data source such as an XML file.

Ad information can come from a variety of sources, such as the following:

An XML file. You can store ad information in an XML file that contains references to ad banners and their associated properties.

Any data source control, such as the SqlDataSource or ObjectDataSource controls. For example, you can store ad information in a database, use a SqlDataSource control to retrieve ad information, and then bind the AdRotator control to the data source control.

Custom logic. You can create a handler for the AdCreated event and select an ad during the event.

XML File Format for Ad Files

Page 4: Best Tutorial of c#

One method of storing ad-banner image locations, URLs for redirection, and associated properties is to put the information in an XML file. By using the XML file format, you can create and maintain a list of advertisements without having to change the code in your application whenever a change is made to an advertisement. For details, see How to: Display Ads From an XML File Using the AdRotator Web Server Control.

Database Schema for Ad Files

Instead of creating an XML file for ad information, you can store ad information in a database table. The table requires a specific schema that the AdRotator control can read. For details, see How to: Display Ads From a Database Using the AdRotator Web Server Control.

Filtering Ads by Keyword

In the advertisement file, you can assign categories to ads by using the Keyword attribute and then configuring the AdRotator control to show ads according to the filter criteria that you specify. For example, if an ad file contains categories for both banks and hardware stores, you might want the page to display only ads that are related to banks. By setting the AdRotator control's KeywordFilter property to "banks," you can have the control filter out the hardware store ads.

If a filter is specified, one of the following two situations can result:

If the AdRotator control can find ads with the matching keyword, an ad with the keyword is displayed.

If no match for the keyword exists, the AdRotator control displays a blank image in the browser.

Tracking Ad Response

The AdRotator control does not inherently provide a way to gather statistics about which ads users have clicked, how many times an ad has been clicked, and so on. However, because you have control over the URL to which the ad points, you can add tracking logic for the ads to your application. A typical way to do this is to point all ads to a tracking page that first gathers the statistics you want, and then jumps to the ad's destination page.

Caching Ads

If the page that contains the AdRotator control is cached, the AdRotator control automatically performs cache substitution to replace the cached ad with a new one whenever the page is retrieved from the cache. For more information, see Dynamically Updating Portions of a Cached Page.

Code Examples

How to: Display Ads From an XML File Using the AdRotator Web Server Control

How to: Display Ads From a Database Using the AdRotator Web Server Control

How to: Select Ads in an AdRotator Web Server Control Programmatically

Page 5: Best Tutorial of c#

Walkthrough: Displaying and Tracking Advertisements with the AdRotator Control

Class Reference

The following table lists the classes that relate to the AdRotator control.

Member Description

AdRotator The main class for the control.

AdCreatedEventHandler Represents the method that handles the AdCreated event of an AdRotator

AdCreatedEventArgs Provides data for the AdCreated event of the AdRotator control.

2) Calendar Web Server Control Overview

The Calendar Web server control can be used to display selectable dates in a calendar and to display data associated with specific dates.

Scenarios

You can use the Calendar Web server control to do the following:

Display and select dates   The control displays a calendar through which users can move to any day in any year. Setting the SelectedDate property causes a specific date to be highlighted in the control. Optionally, users can move to arbitrary dates by clicking a day or moving from month to month. The calendar can be configured to enable users to select multiple dates, either a whole week or a whole month.

A representation of the Calendar control displaying the month of October

Page 6: Best Tutorial of c#

Display appointments or other information in a calendar grid   The Calendar control can display specific details for individual days, such as a to-do list, a schedule of events, or similar information. This feature enables you to display day information from a database.

Features

You can use the Calendar control to do the following:

Capture user interaction such as when a user selects a date or a range of dates. Customize the calendar's appearance. Display information from a database in the calendar.

Background

The Calendar control displays the dates for one month at a time, with a total of six weeks appearing at the same time. The control supports several types of dates, which are described in the following table.

Type of date Description

TodaysDate By default, this is set to match the current date on the server. However, you can adjust it so that the date appears correctly for a different locale.

VisibleDate This date determines which month appears in the calendar. The user can move from month to month on the calendar, which changes the visible date without affecting today's date. You can navigate between months by setting the visible date programmatically.

SelectedDate,SelectedDates

This is the date or date range that the user chooses. In the control, the user can select a single day, week, or month, but can only select contiguous dates. You can also programmatically set the selected dates. In that case, you can set non-contiguous selected dates.

The Calendar control is based on the DateTime object, and therefore supports the full range of dates that is allowed by that object. Effectively, you can display any date between the years 0 and 9999 A.D.

On an ASP.NET page, the Calendar control is rendered as an HTML table. Therefore, some the control's properties pertain to various aspects of table formatting. A few of these properties are not fully supported in some older browsers. Therefore, not all the formatting features will be available in those browsers.

Enabling Date Selection

By default, the calendar enables users to click an individual date to select it. If you are using the control as a read-only calendar, you can disable the date-selection functionality.

If date selection is enabled, each day of the calendar contains a LinkButton control that raises an event when it is clicked. If you enable week or month selection, a column of links is added to the side of the calendar to enable the user to specify which week to select.

Page 7: Best Tutorial of c#

Customizing the Calendar's Appearance

You can set calendar properties to change the colors, size, text, and other visual features of the calendar. There are several ways to do this, as shown in the following table.

Customization method

Description

Setting properties You can set properties to display gridlines, change which day is displayed as the first day of the week, and change the appearance of the month and day names.

Setting extended style properties

You can use properties derived from the Style object to set the appearance of particular elements in the calendar. This includes the current date or the title bar that contains the month and navigation links. These style properties are supported in browsers that can use cascading style sheets. A reduced set of appearance styles is supported for earlier browsers.

Customizing the rendering of individual days

As the control renders individual days, it raises an event that you can handle to modify the stream that is being rendered. This is useful not just for changing the appearance of days, but for including custom content on each day. For details, seeCustomize Individual Days in a Calendar Web Server Control.

Capturing User Interaction with the Calendar Web Server Control

The Calendar control raises the SelectionChanged event when the user selects an individual date or range of dates. It raises the VisibleMonthChanged event when the user displays a new month. By creating methods for these events, you can determine what date or dates the user has selected and respond appropriately. One response might be to customize the display of that date.

Displaying Information from a Database in the Calendar Control

A common scenario is to display information from a database in the calendar. For example, an events calendar is often based on information that is stored in a database.

The Calendar control does not directly support data binding — that is, you do not bind the calendar as a whole to a data source. Instead, you create a method for the control's DayRender event, which is raised as each day in the current calendar month is being rendered. In the handler for this event, you can extract information from a data source and add it to the stream being rendered to the browser. For details, see How to: Display Selected Dates from a Database in the Calendar Control.

Accessibility

To make the Calendar control more accessible to users of assistive devices, the control supports a property named UseAccessibleHeader. When this property is set to true (which is the default setting), the column headings that contain the names of days are rendered using HTML th elements.

Code Examples

How to: Control Month Navigation in a Calendar Web Server Control How to: Control User Date Selection in a Calendar Web Server Control

Page 8: Best Tutorial of c#

How to: Customize Calendar Web Server Control Appearance How to: Customize Individual Days in a Calendar Web Server Control How to: Format Calendar Web Server Control Elements Using Styles How to: Respond to Date Selection in a Calendar Web Server Control How to: Read Selected Dates in the Calendar Web Server Control How to: Select Dates Programmatically in a Calendar Web Server Control How to: Set Today's Date Programmatically in a Calendar Web Server Control How to: Display Selected Dates from a Database in the Calendar Control

Class Reference

The following table lists the classes that relate to the Calendar control.

Member Description

Calendar The main class for the control.

CalendarDay The class that represents a date in the Calendar control.

CalendarSelectionMode An enumeration that represents the date selection modes available in the Calendar

3) BulletedList Web Server Control Overview

The BulletedList control creates an unordered or ordered (numbered) list of items, which render as HTML ul or ol elements, respectively.

Scenarios

Use the BulletedList control to do the following:

Specify the appearance of the items and of the bullets or numbers in a list. Define the list items statically or by binding the control to data. Respond to user clicks on items.

Features

When using the BulletedList control, you can do the following:

Customize the appearance of the bullets and numbers. Specify how each item in the list is rendered, such as a hyperlink, static text, or as a

link button. Provide logic to perform application-specific tasks when a user clicks an item.

Background

Page 9: Best Tutorial of c#

The BulletedList control derives from the same ListControl class as the ListBox, DropDownList, and other ASP.NET list controls. Therefore, using the BulletedList control is like working with those controls. You can define list items for the BulletedList control either by creating static items or by binding the control to a data source. If you know at design time what items that you want to display, you can set the control's Items collection to a set of individual items in markup. If the items to be displayed are dynamic, you can create the item collection in code at run time. For details, see How to: Add Items in List Web Server Controls.

Alternatively, you can bind the control to a data source that contains the information that you want to display. For details, see How to: Populate List Web Server Controls from a Data Source.

You can combine static and data-bound list items by setting the control's AppendDataBoundItems property to true.

When you define items for the BulletedList control, you define two properties: the Text property and the Value property. The Text property defines what the control displays on the page. The Value property defines a second value that is not displayed but that you might want to return when a user selects an item. For example, you might display an employee name as the text of an item, but use the employee ID as the value. When users click the item, you can read the value directly.

Security NoteDo not use sensitive data, such as customer numbers, for the value property of a BulletedList control. Even though it is not visible, theof individual items are rendered to the page, where users can easily read them in the page's source.

Customizing List Item Appearance

The BulletedList control can render either bullets or numbers, according to the setting of the BulletStyle property. If the control is set to render bullets, you can select from predefined bullet style fields that match HTML standard bullet styles, such as those represented by the Disc, Circle, and Square fields.

NoteIndividual browsers vary in how they render bullets, and some browsers do not support certain bullet styles, such as the

You can also specify a custom image that will be displayed instead of the bullet.

If the control is set to render numbers, you can select from HTML standard numbering options, such as the LowerAlpha, UpperAlpha, LowerRoman, and UpperAlpha fields. By setting the FirstBulletNumber property, you can also specify a starting number for the sequence.

Specifying Item Display Mode

The BulletedList control can display list items as any one of the following:

Page 10: Best Tutorial of c#

Static text   The text displayed by the control is not interactive. T:System.Web.UI.WebControls.HyperLink controls   Users can click links to move to

another page. You must provide a target URL as the Value property of individual items.

LinkButtoncontrols   Users can click individual items and the control performs a postback.

Responding to User Selection

If the BulletedList control is configured to display individual items as LinkButton controls, the control performs a postback when a user clicks an item. The postback raises theBulletedList control's Click event, where you can provide logic to perform application-specific tasks. The event passes to you the index number of the item that was clicked. For details, see How to: Respond to User Clicks in BulletedList Web Server Controls.

How-to and Walkthrough Topics

How to: Add BulletedList Web Server Controls to a Web Forms Page How to: Respond to User Clicks in BulletedList Web Server Controls

Class Reference

The following table lists the classes that relate to the BulletedList control.

Member Description

BulletedList The main class for the control.

BulletedListDisplayMode An enumeration that specifies the display behavior of each item.

BulletedListEventArgs The event data that indicates the index of the selected item.

BulletedListEventHandler The method that handles the Click event of a BulletedList control.

BulletStyle An enumeration that specifies the types of bullets, numbers, or letters that can be displayed.

4) Button Web Server Controls Content Map

Use the ASP.NET button Web server controls to enable users to post a page to the server. The button controls trigger an event in server code that you can handle to respond to the postback. For example, a user can indicate that they have completed a form or that they want to perform a specific command. The Button control can also raise an event in client script that you can handle before the page is posted or that can run and then cancel submission of the page.

Types of Button Controls

Page 11: Best Tutorial of c#

ASP.NET includes several kinds of button controls, each of which appears differently on Web pages, as listed in the following table:

Control Description

Button Presents a standard command button, which is rendered as an HTML

LinkButton Renders as a hyperlink in the page. However, it contains client-side script that causes the form to be posted back to the server. (You can create a true hyperlink by using the HyperLink Web server control.)

ImageButton Renders a graphic as a button. This is useful for presenting a rich button appearance. Theprovides information about the coordinates within the graphic where has clicked.

HtmlButton, HtmlInputButton, or HtmlInputImage

HTML button elements that you can program as ASP.NET Web server controls.

For information about the differences between HTML and Web server controls, seeOverview.

ImageMap Lets you create a graphic that has hotspots that users can click to perform a postback or other action.

Note

The ImageMap control lets you create a graphic that has hotspots that users can click in order to post a page or to perform other actions.

Button Control Tasks

The following table lists tasks that are often performed using ASP.NET Web server button controls.

Scenario Implementation

Respond to a button event. Create a handler in server code for the button's Click event or

Determine which button among several caused the postback.

In a handler for the button's Click event or Command event, cast thetype (Button, LinkButton, or ImageButton) and then get the ID of the object.

Run client script after a button is clicked and before the page is posted (for example, to display a confirmation message).

Add JavaScript code to the button's OnClientClick property. To cancel a postback in client script, return falsefrom the client code.

Determine the coordinates in an image button where a user clicked.

Use an ImageButton control and in the button's Click event, get thethe ImageClickEventArgsobject that is passed to the event handler. For more information, see the example in the

In response to a button click, post to a different page than the one that the button is on.

Set the button's PostBackUrl property. For more information, see

Specify whether a button click causes user input to be validated.

Enable or disable the button's CausesValidation property.

Page 12: Best Tutorial of c#

Determine which controls on the page perform validation in response to a button click.

Set the button's ValidationGroup property to match the name that is used with a validation control.

Configure a button to cause a partial-page postback. Include the button inside an UpdatePanel control or put it outside thebe a trigger. For more information, see UpdatePanel Control OverviewOverview.

5) CheckBox and CheckBoxList Web Server Controls Overview

The CheckBox control and the CheckBoxList control provide a way for users to specify yes/no (true/false) choices.

Features

You can use the CheckBox control and the CheckBoxList control to:

Cause a page postback when a check box is selected. Capture user interaction when a user selects a check box. Bind each check box to data from a database.

Background

You can use two types of Web server controls to add check boxes to an ASP.NET Web page: individual CheckBox controls or a CheckBoxList control. Both controls provide a way for users to specify yes/no (true/false) choices.

You add individual CheckBox controls to a page and work with them singly. Alternatively, you can use the CheckBoxList control, which is a single control that acts as a parent control for a collection of check-box list items. It derives from the base ListControl class, and therefore works much like the ListBox, DropDownList, RadioButtonList, andBulletedList Web server controls. Many of the procedures for working with the CheckBoxList control are the same as the procedures for the other list server controls.

Both types of controls have advantages. By using individual CheckBox controls, you get more control over the layout of the check boxes on the page than by using the CheckBoxList control. For example, you can include non-check-box text between each check box. You can also control the font and color of individual check boxes.

The CheckBoxList control is a better choice if you want to create a series of check boxes from data in a data source. (You can bind an individual CheckBox control to data.)

Note

Page 13: Best Tutorial of c#

You can also use the HtmlInputCheckBox control to add check boxes to an ASP.NET Web page. For more information, seeControl Declarative Syntax.

CheckBox and CheckBoxList Events

Events work differently between individual CheckBox controls and the CheckBoxList control.

CheckBox Control Events

Individual CheckBox controls raise the CheckedChanged event when users click the control. By default, this event does not cause the page to be posted to the server. However, you can force the control to perform an immediate postback by setting the AutoPostBack property to true. For more information, see How to: Respond to User Selection in a CheckBox Web Server Control.

Note

The auto-postback capability requires that the browser support ECMAScript (JScript, or JavaScript) and that scripting be enabled on the user's browser.

You might not need to create an event handler for the CheckedChanged event. You can test which check box is selected in any code that runs as part of the page. Typically, you create an event handler for the CheckedChanged event only if you need to know that the check box was changed, not just to read the value of a check box. For details, see How to: Set and Get the Selection in a RadioButton Web Server Control.

CheckBoxList Control Events

The CheckBoxList control raises a SelectedIndexChanged event when users select any check box in the list. By default, the event does not cause the page to be posted to the server. However, you can force the control to perform an immediate postback by setting the AutoPostBack property to true.

Note

The auto-postback capability requires that the browser support ECMAScript (JScript, or JavaScript) and that scripting be enabled on the user's browser.

As with individual CheckBox controls, it is more common to test the state of the CheckBoxList control after the page has been posted some other way. For details, see How to: Determine the Selection in List Web Server Controls.

CheckBox Control HTML Attributes

Page 14: Best Tutorial of c#

When the CheckBox control renders to the browser, it does so in two parts: an input element that represents the check box, and a separate label element that represents the caption for the check box. The combination of the two elements is wrapped in a span element.

When you apply style or attribute settings to a CheckBox control, the settings are applied to the outer span element. For example, if you set the control's BackColor property, the setting is applied to the span element. Therefore, it affects both the inner input and label attributes.

At times, you might want to apply separate settings to the check box and to the label. The CheckBox control supports two properties that you can set at run time. TheInputAttributes property lets you add HTML attributes to the input element, and the LabelAttributes property lets you add HTML attributes to label element. The attributes that you set are passed through as-is to the browser. The following example shows how to set attributes for the input element so that only the check box, but not the label, changes color when users pass the mouse pointer over it.

Copy

CheckBox1.InputAttributes.Add("onmouseover", _ "this.style.backgroundColor = 'red'")CheckBox1.InputAttributes.Add("onmouseout", _ "this.style.backgroundColor = 'white'")

C#

CheckBox1.InputAttributes.Add("onmouseover", "this.style.backgroundColor = 'red'");CheckBox1.InputAttributes.Add("onmouseout", "this.style.backgroundColor = 'white'");

Binding Data to the Controls

You can bind an individual CheckBox control to a data source, and you can bind any property of the CheckBox control to any field of the data source. For example, you typically set the control's Checked property based on information in a database.

You can also bind a CheckBoxList control to a data source. In that case, the check boxes each represent a different record in the data source.

Code Examples

How to: Add CheckBox Web Server Controls to a Web Forms Page

How to: Add CheckBoxList Web Server Controls to a Web Forms Page

How to: Set Layout in a CheckBoxList Web Server Control

How to: Get and Set a CheckBox Web Server Control Value Programmatically

How to: Respond to User Selection in a CheckBox Web Server Control

Page 15: Best Tutorial of c#

How to: Add Items in List Web Server Controls

How to: Populate List Web Server Controls from a Data Source

How to: Respond to Changes in List Web Server Controls

Class Reference

The following table lists the classes that relate to the CheckBox and CheckBoxList controls.

Member Description

CheckBox The main class for the CheckBox control.

CheckBoxList The main class for the CheckBoxList control.

ListItem The class that represents each item in CheckBoxList control.

Items The collection of items that correspond to individual items in the list for a CheckBoxList 

6) FileUpload Web Server Control Overview

The FileUpload control enables you to provide users with a way to send a file from their computer to the server.

Features

You can use the FileUpload control to:

Enable users to upload files that you store on a specific location on the server. Limit the size of the file that can be uploaded. Examine the properties of an uploaded file before storing the file.

Background

The FileUpload control enables users to upload pictures, text files, or other files. The FileUpload control displays a text box where users can type the name of a file that they want to upload to the server. The control also displays a Browse button that displays a file-navigation dialog box. (The dialog box that is displayed depends on the operating system of the user's computer.) For security reasons, you cannot pre-load the name of a file into the FileUpload control.

Handling Uploaded Files

Page 16: Best Tutorial of c#

When users have selected a file to upload and then submitted the page, the file is uploaded as part of the request. The file is cached in its entirety in server memory. When the file has finished uploading, your page code runs.

You can access the uploaded file in the following ways:

As a byte array exposed in the FileUpload control’s FileBytes property. As a stream exposed in the FileContent property. As an object of type HttpPostedFile in the PostedFile property. The PostedFile object

exposes properties, such as the ContentType and ContentLength properties, that provide you with information about the uploaded file.

When your code runs, you can examine the characteristics of the file, such as its name, size, and MIME type, and you can then save it. You can work with the file as a byte array or stream. Alternatively, both the FileUpload control and the HttpPostedFile object support a SaveAs method that writes the file to disk.

There is no inherent limitation on where you can save uploaded files. However, to save the file, the ASP.NET process must have permission to create files in the location that you specify. In addition, your application might be configured to require an absolute path (not a relative path) for saving the file, which is a security measure. If therequireRootedSaveAsPath attribute of the httpRuntime configuration element is set to true (which is the default), you must provide an absolute path when saving the uploaded file.

NoteYou can create an absolute path based on the root of your application by using the MapPath method of the HttpServerUtilitythe tilde (~) operator, which represents the application root folder. For more information, see ASP.NET Web Site Paths

The maximum size file that can be uploaded depends on the value of the MaxRequestLength configuration setting. If users attempt to upload a file that is larger than the maximum allowed, the upload fails.

Using the FileUpload Control in Partial-Page Updates

The FileUpload control is designed to be used only in postback scenarios and not in asynchronous postback scenarios during partial-page rendering. When you use a FileUploadcontrol inside an UpdatePanel control, the file must be uploaded by using a control that is a PostBackTrigger object for the panel. UpdatePanel controls are used to update selected regions of a page instead of updating the whole page with a postback. For more information, see UpdatePanel Control Overview and Partial-Page Rendering Overview.

Security and the FileUpload Control

By using the FileUpload control, users can upload potentially malicious files, including script files and executable files. You cannot limit in advance the files that a user can upload. If you want to limit the types of files that a user can upload, you must examine the file characteristics after the file has been uploaded, such as the file's file name extension and the value of the file's ContentType property

Page 17: Best Tutorial of c#

NoteBefore the page is submitted, you can use client script to examine the file name that a user has typed in the text box. However, although performing a client-side check of the file name can be useful, it does not guarantee that users cannot upload an unsafe file type, such as an executable file.

Code Examples

How to: Upload Files with the FileUpload Web Server Control

Class Reference

The following table lists the classes that relate to the FileUpload control.

Member Description

FileUpload The main class for the FileUpload control.

7) HiddenField Web Server Control Overview

The HiddenField control provides you with a way to store information in the page without displaying it. For example, you might store a user-preference setting in a HiddenFieldcontrol so that it can be read in client script. To put information into a HiddenField control, you set its Value property to the value you want to store between postbacks.

Features

You can use the HiddenField control to:

Store data in a hidden field on a page. Detect when data stored in the hidden field has changed between postbacks.

Background

The information in a HiddenField control is not displayed when the browser renders the page. However, it can be read and set in client script. When the page is posted back, the contents of the HiddenField control, which includes any changes made in client script, are available in server code.

NoteAlthough the information in a hidden field is not displayed, users can see the contents of the control by viewing the page's source. Do not store sensitive information in aHiddenField control, such as user IDs, passwords, or credit card information.

Page 18: Best Tutorial of c#

Detecting Changed Data

The value of a HiddenField control can be changed before the page is posted back to the server. This might occur because you are using the hidden field to share information between server code and client script, and client script has updated the value of the control.

To help you detect changes to data in the control, the HiddenField control raises a ValueChanged event if the value of the control changes between postbacks. You can handle this event to determine whether a value has changed.

Class Reference

The following table lists the classes that relate to the HiddenField control.

Member Description

HiddenField The main class for the control.

8) HyperLink Web Server Control Overview

The HyperLink Web server control creates links on a Web page that enables users to move from page to page in an application.

Background

The primary advantage of using a HyperLink control is that you can set link properties in server code. For example, you can dynamically change the link text or target page based on conditions in the page.

Security NoteThe URLs associated with a hyperlink can be tampered with by a malicious user. For more information, see How to: Protect Against Script Exploits in a Web Application by Applying HTML Encoding to Strings.

Another advantage of using the HyperLink control is that you can use data binding to specify the target URL for the link (and parameters to be passed with the link, if necessary). A typical example is to create HyperLink controls based on a list of products. The target URL points to a page where the user can read more detail about the product.

TipIf you need to create data-bound HyperLink controls, a convenient way to do so is to add them as children of these

Page 19: Best Tutorial of c#

controls: Repeater, DataList, GridView, FormView, orDetailsView.

The HyperLink control can display clickable text or an image.

Unlike most Web server controls, the HyperLink control does not raise an event in server code when users click it. Instead, the control simply performs navigation.

Code Examples

How to: Add HyperLink Web Server Controls to a Web Forms Page

Class Reference

The following table lists the classes that relate to the HyperLink control.

Member Description

HyperLink The main class for the control.

9) Image Web Server Control Overview

The Image Web server control enables you to display images on an ASP.NET Web page and manage these images in your own code.

Background

You can specify the graphics file for an Image control at design time or at run time programmatically. You can also bind the control's ImageUrl property to a data source to display graphics based on database information.

Unlike most other Web server controls, the Image control does not support any events. For example, the Image control does not respond to mouse clicks. Instead, you can create an interactive image by using the ImageMap or the ImageButton Web server controls.

Specifying Text Elements

In addition to displaying a graphic, the Image control enables you to specify various types of text for the image, such as the following:

ToolTip   The text that is displayed in a tooltip in some browsers. AlternateText   The text that is displayed if the graphics file cannot be found. If

no ToolTip property is specified, some browsers will use the AlternateText value as a tooltip.

If the GenerateEmptyAlternateText property is set to true, the alt attribute of the rendered image element will be set to an empty string.

Page 20: Best Tutorial of c#

Code Examples

How to: Add Image Web Server Controls to a Web Forms Page

Class Reference

The following table lists the classes that relate to the Image control.

Member Description

Image The main class for the control.

ImageAlign An enumeration that represents the alignment options for an image relative to the text of a Web page.

10) ImageMap Web Server Control Overview

The ASP.NET ImageMap control enables you to create an image that has individual regions that users can click, which are called hot spots. Each of these hot spots can be a separate hyperlink or postback event.

Background

The ImageMap control consists of two pieces. The first is an image, which can be a graphic in any standard Web graphic format, such as a .gif, .jpg, or .png file.

The second element is a collection of HotSpot controls. Each hot-spot control is a different item that is of type CircleHotSpot, RectangleHotSpot, or PolygonHotSpot. For each hot-spot control, you define the coordinates that specify the location and size of the hot spot. For example, if you create a CircleHotSpot control, you define the x-coordinates and y-coordinates of the circle's center and the circle's radius.

You can define as many or as few hot spots for the image as you require. You do not have to define hot spots to cover the graphic entirely.

NoteYou can define overlapping hot spots. Each hot spot has a z-index value. If a user clicks an area that is defined by two or more overlapping hot spots, the hot spot with the highest z-order is the hot spot that is selected.

Responding to User Clicks

You can specify what happens when a user clicks a hot spot. You can configure each hot spot as a hyperlink that goes to a URL that you provide for that hot spot. Alternatively, you

Page 21: Best Tutorial of c#

can configure the control to perform a postback when a user clicks a hot spot, and provide a unique value for each hot spot. The postback raises the ImageMap control'sClick event. In the event handler, you can read the unique value that you assign to each hot spot.

Code Examples

How to: Add ImageMap Web Server Controls to a Web Page

How to: Respond to User Clicks in ImageMap Web Server Controls

Class Reference

The following table lists the classes that relate to the ImageMap control.

Member Description

ImageMap The main class for the control.

CircleHotSpot Represents an individual hotspot that is a circle.

RectangleHotSpot Represents an individual hotspot that is a rectangle.

PolygonHotSpot Represents an individual hotspot that is a polygon.

11) Label Web Server Control Overview

The Label Web server control lets you programmatically set text in an ASP.NET Web page.

Scenarios

You typically use the Label control when you want to change text in the page at run time, such as in response to a button click.

Features

You can set the text of the Label control at design time or at run time in a program. You can also bind the Label control's Text property to a data source to display database information on a page.

Background

You can use the Label control to act as an active caption in front of a TextBox control or other control. Users can then press an access key to move to the control for which theLabel control is the caption. For details, see How to: Use Label Web Server Controls as Captions.

Page 22: Best Tutorial of c#

The Label control provides one way to display text in an ASP.NET Web page. Other options include the following:

HTML markup   If you want to display static text, you can present it using HTML; you do not need a Label control. Use a Label control only if you need to change the contents or other characteristics of the text in server code.

TheLiteral control   Like the Label control, the Literal control lets you programmatically display text in the page. However, the Literal control does not support style properties and does not support themes or skins.

Using Labels in List Controls

The Label control is often used in list Web server controls (such as the Repeater, DataList, GridView, DetailsView, and FormView controls) to display read-only information from a database. The usual strategy is to add a Label control to a template for one of these controls. You then bind the Label control to a data source. For details about templates, seeASP.NET Web Server Controls Templates.

Security and the Label Control

You can set the Text property of the Label control to any string, including strings that contain markup. If the string contains markup, the Label control interprets the markup. For example, if you set the Text property to <b>Test</b>, the Label control renders the word Test in bold type.

To avoid security issues such as the possibility of script injection, do not set the Text property to a string that contains markup that comes from an untrusted source. If you do not trust the source of the string that you are using for the Text property, you should encode the string. For details, see How to: Protect Against Script Exploits in a Web Application by Applying HTML Encoding to Strings.

Code Examples

How to: Add Label Web Server Controls to a Web Forms Page

How to: Use Label Web Server Controls as Captions

Class Reference

The following table lists the classes that relate to the Label control.

Member Description

Label The main class for the control.

12) ListBox Web Server Control Overview

Page 23: Best Tutorial of c#

The ListBox Web server control enables users to select one or more items from a predefined list.

Scenarios

Use the ListBox Web server control when you want to display multiple items at once and to enable users to select one or more items from a predefined list. The ListBox control differs from a DropDownList control in that it can display multiple items at once and that it optionally enables the user to select multiple items.

Features

You can use the ListBox control to:

Set the control to display a specific number of items. Set the size of the control in pixels. Use data-binding to specify the list of items to display. Determine which item or items are selected. Specify the selected item or items programmatically.

Background

The ListBox control is typically used to display more than one item at once. You can control the look of the list in these ways:

Number of rows displayed. You can set the control to display a specific number of items. If the control contains more items than that, it displays a vertical scroll bar.

Height and width. You can set the size of the control using pixels. In that case, the control ignores the number of rows you have set and displays as many as will fit into the height of the control. Some browsers do not support setting the height and width in pixels and will use the row count setting.

As with other Web server controls, you can use style objects to specify the appearance of the control. For details, see ASP.NET Web Server Controls and CSS Styles.

List Items

The ListBox control is a container for one or more list items. Each list item is an object of type ListItem with its own properties. These properties are described in the following table.

Property

Description

Text Specifies the text that is displayed in the list.

Value Contains the value that is associated with an item. Setting this property enables you to associate a value with a specific item without displaying it. For example, you can set the Text property to the name of a color and the Value property to its hexadecimal representation.

Selected Indicates whether the item is currently selected.

Page 24: Best Tutorial of c#

To work with items programmatically, you work with the Items collection of the ListBox control. The Items collection is a standard collection, and you can add item objects to it, delete items, clear the collection, and so on.

The currently selected item is available in the ListBox control's SelectedItem property. If the control is set to single-selection mode, this property returns the one selected item. If the control is set to multi-selection mode, you get the selected items by looping through the entire Items collection and examining the Selected property of each item.

Single versus Multiple Selection

Users can normally select a single item in the list by clicking it. If you set the ListBox control to enable multiple selections, users can hold down the CTRL or SHIFT key while clicking to select multiple items.

Binding Data to the Control

You can use a ListBox Web server control to list options that are made available to the page using a data source control. Each item in the ListBox control corresponds to an item in the data source, typically an individual data record.

The control displays one field from the source. Optionally, you can bind the control to a second field to set the value of an item, which is not displayed.

As with other server controls, you can bind any control properties, such as the color or size of the control, to data. For details, see How to: Populate List Web Server Controls from a Data Source.

ListBox Events

The ListBox control raises the SelectedIndexChanged event when users select an item. By default, this event does not cause the page to be posted to the server, but you can cause the control to force an immediate postback by setting the AutoPostBack property to true.

NoteThe auto-postback capability requires that the browser support ECMAScript (JScript, or JavaScript) and that scripting be enabled on the user's browser.

Code Examples

How to: Add ListBox Web Server Controls to a Web Forms Page

How to: Add Items in List Web Server Controls

How to: Set the Selection in List Web Server Controls

How to: Populate List Web Server Controls from a Data Source

How to: Respond to Changes in List Web Server Controls

How to: Determine the Selection in List Web Server Controls

Page 25: Best Tutorial of c#

Back to top

Class Reference

The following table lists the classes that relate to the ListBox control.

Member Description

ListBox The main class for the control.

ListItem The class that represents each item in the list.

13) Literal Web Server Control Overview

You can use a Literal Web server control as a container for other content on the page.

Scenarios

The Literal control is used most frequently when adding content dynamically to the page.

Background

The Literal control represents one of several options for adding content to a page. For static content, you can add markup directly to a page as HTML, without using a container. However, if you want to add content dynamically, you must add the content to a container. Typical containers are the Label control, the Literal control, the Panel control, and thePlaceHolder control.

The Literal control differs from the Label control in that the Literal control does not add any HTML elements to the text. (The Label control renders a span element.) As a consequence, the Literal control does not support any style attributes, including position attributes. However, the Literal control enables you to specify whether content is encoded.

The Panel and PlaceHolder controls render as div elements, which create discrete blocks in the page, unlike rendering in-line the way the Label and Literal controls do.

In general, use a Literal control when you want to render text and controls directly into a page without any additional markup.

Encoding Content in the Literal Control

The Literal control supports the Mode property, which specifies how the control handles markup that you add to it. You can set the Mode property to these values:

Transform. Any markup that you add to the control is transformed to accommodate the protocol of the requesting browser. This setting is useful if you are rendering content to mobile devices that use protocol other than HTML.

Page 26: Best Tutorial of c#

PassThrough. Any markup that you add to the control is rendered as-is to the browser.

Encode. Any markup that you add to the control is encoded using the HtmlEncode method, which converts HTML encoding into its text representation. For example, a <b>tag is rendered as &lt;b&gt;. Encoding is useful when you want the browser to display markup rather than interpret it. Encoding is also useful for security, to help prevent malicious markup from being executed in the browser. It recommended if you are displaying strings from an untrusted source. For more information, see How to: Protect Against Script Exploits in a Web Application by Applying HTML Encoding to Strings.

Code Examples

How to: Add Literal Web Server Controls to a Web Forms Page

Class Reference

The following table lists the classes that relate to the Literal control.

Member Description

Literal The main class for the control.

14) Localize Web Server Control Overview

The Localize Web server control lets you display localized text in a specific area on your page.

Background

The Localize control is identical to the Literal Web server control and similar to the Label Web server control. Although the Label control lets you apply a style to the displayed text, the Localize control does not. You can programmatically control the text that is displayed in the Localize control by setting the Text property, which is inherited from theLiteral control.

Encoding Content

The Localize control supports the Mode property, which specifies how the control handles markup that you add to it. You can set the Mode property to the following values:

Transform  Any markup that you add to the control is transformed to accommodate the protocol of the requesting browser. This setting is useful if you are rendering content to mobile devices that use a protocol other than HTML.

Page 27: Best Tutorial of c#

PassThrough  Any markup that you add to the control is rendered as-is to the browser.

Encode  Any markup that you add to the control is encoded using the HtmlEncode method, which converts HTML encoding into its text representation. For example, a <b>tag is rendered as &lt;b&gt;. Encoding is useful when you want the browser to display markup rather than interpret it. Encoding is also useful for security and to help prevent malicious markup from being executed in the browser. It is recommended if you are displaying strings from an untrusted source. For more information, see How to: Protect Against Script Exploits in a Web Application by Applying HTML Encoding to Strings.

Localizing Text By Using Resource Strings

You can create localized strings to display in the Text property of the Localize control by using an explicit or implicit expression as the value of the property. Expressions are evaluated by using strings that are declared in resource (.resx) files.

Create .resx files in folders named App_GlobalResources and App_LocalResources in the root of your application. If you have to localize strings for multiple languages, you can create additional .resx files with locale information included in the file name. For example, the French version of your resource file would be named ExampleLocalizedStrings.fr.resx.

For more information about expressions, see ASP.NET Expressions Overview. For information about resource files, see Localizing ASP.NET Web Pages By Using Resources. For a code example that uses regular expressions in the Localize control, see Localize Web Server Control Declarative Syntax.

Code Examples

How to: Add Localize Web Server Controls to ASP.NET Web Pages

Class Reference

The following table lists the classes that relate to the Localize control.

Member Description

Localize The main class for the control.

15) MultiView and View Web Server Controls Overview

The MultiView and View Web server controls act as containers for other controls and markup, and provide a way for you to easily present alternate views of information.

Page 28: Best Tutorial of c#

Scenarios

You can use the MultiView and View controls to perform tasks such as the following:

Provide alternate sets of controls based on user choice or other conditions. For example, you might allow users to select from a list of feeds, each of which is configured in a separate View control. You can then display the View control that contains the user's choice of feeds. You can use the MultiView and View controls as an alternative to creating multiple Panel controls.

Create a multi-page form. The MultiView and View controls can provide behavior that is similar to the Wizard control. The Wizard control is particularly suited to creating forms that users fill in step by step. The Wizard control also includes support for more built-in UI elements, such as a header and footer, for Previous and Next buttons, and for templates. You might use a MultiView control in place of a Wizard if you wanted to create a display that changed based on condition (rather than sequentially), or if you did not need the extra features supported by the Wizard control.

Background

The MultiView control acts as an outer container for one or more View controls. The View controls, in turn, can contain any combination of markup and controls.

The MultiView control displays one View control at a time, exposing the markup and controls within that View control. By setting the MultiView control's ActiveViewIndex property, you can specify which View control is currently visible.

Rendering View Control Content

If a View control is not selected, it is not rendered to the page. However, instances of all Web server controls in all the View controls are created each time the page is rendered, and their values are stored as part of the page's view state.

Neither the MultiView control nor individual View controls render any markup to the page other than the contents of the current View control. For example, the controls do not render a div element in the same way that a Panel control does. They also do not support appearance properties that can be applied as a whole to the current View control. But you can assign a theme to the MultiView or View controls, which applies the theme to all child controls of the current View control.

Referencing Controls

Each View control supports a Controls property that contains a collection of the controls in that View control. You can also reference the controls in the View controls individually in code. For details, see Accessing ASP.NET Controls Programmatically.

Navigating Between Views

You can move between views by setting the MultiView control's ActiveViewIndex property to the index value of the View control to display. The MultiView control also includes support for navigation buttons that you can add to each View control.

Page 29: Best Tutorial of c#

To create navigation buttons, you can add a button control (Button, LinkButton, or ImageButton) to each View control. You can then set the CommandName andCommandArgument properties of each button to reserved values to cause the MultiView control to move to another view. The following table lists the reserved CommandNamevalues and the corresponding CommandArgument values.

CommandName value CommandArgument value

NextView (no value)

PrevView (no value)

SwitchViewByID ID of the View control to switch to.

SwitchViewByIndex Index number of the View control to switch to.

The following code example shows a MultiView control with three View controls. Each View control contains a Button control that moves to a specific View control.

Copy<asp:MultiView ID="MultiView1" runat="server" ActiveViewIndex="0"> <asp:View ID="View1" runat="server"> View 1<br /> <br /> <asp:Button ID="Button1" runat="server" CommandArgument="View2" CommandName="SwitchViewByID" Text="Go to View2" /> </asp:View> <asp:View ID="View2" runat="server"> View 2<br /> <br /> <asp:Button ID="Button2" runat="server" CommandArgument="View3" CommandName="SwitchViewByID" Text="Go to View 3" /> </asp:View> <asp:View ID="View3" runat="server"> View 3<br /> <br /> <asp:Button ID="Button3" runat="server" CommandArgument="View1" CommandName="SwitchViewByID" Text="Go to View 1" /> </asp:View></asp:MultiView>

Code Examples

How to: Add MultiView Web Server Controls to a Web Forms Page

Class Reference

Page 30: Best Tutorial of c#

The following table lists the classes that relate to the MultiView and View controls.

Member Description

MultiView The main class for the MultiView control.

ViewCollection Represents a collection that enables a MultiView control to maintain a list of its child controls.

View The main class for the View control.

MultiViewControlBuilder Interacts with the parser to build a MultiView control. To create a custom control builder for ato inherit from this class.

16) Panel Web Server Control Overview

The Panel Web server control provides a container control in an ASP.NET Web page that you can use as a parent for static text and for other controls.

Background

You can use the Panel control as a container for other controls. This is particularly useful when you are creating content programmatically and you need a way to insert the content into the page. The following sections describe additional ways that you can use the Panel control.

Container for Dynamically Generated Controls

The Panel control provides a convenient container for controls that you create at run time. For details, see Adding ASP.NET Controls Programmatically.

Grouping Controls and Markup

You can manage a group of controls and associated markup as a unit by putting them in a Panel control and then manipulating the Panel control. For example, you can hide or show a group of controls inside a panel by setting the panel's Visible property.

Forms with Default Buttons

You can put TextBox controls and Button controls inside the Panel control and then define a default button by setting the Panel control's DefaultButton property to the ID of a button in the panel. If users press ENTER while typing in a text box inside the panel, it has the same effect as if the user had clicked the specified default button. This can help users work more efficiently with entry forms.

Adding Scrollbars to Other Controls

Some controls such as the TreeView control do not have built-in scrollbars. You can add scrolling behavior by placing the control in a Panel control. To add scrollbars to

Page 31: Best Tutorial of c#

the Panelcontrol, set the Height and Width properties to constrain the Panel control to a specific size, and then set the ScrollBars property.

Custom Areas on the Page

You can use the Panel control to create areas on the page that have custom appearance and behavior, such as the following:

Creating a grouping box with title   You can set the GroupingText property to display a title. When the page renders, the Panel control is displayed with a box around it that contains a title with the text you specify.

NoteYou cannot specify both scrollbars and grouping text in the Panel control. If you set grouping text, it takes precedence over scrollbars.

Creating areas on the page with a custom color or other appearance   The Panel control supports appearance properties such as BackColor and BorderWidth that you can set to create a unique look for a region on a page.

NoteSetting the GroupingText property automatically renders a border around the Panel control.

Code Examples

How to: Add Panel Controls to a Web Forms Page

How to: Add Controls to an ASP.NET Web Page Programmatically

Class Reference

The following table lists the classes that relate to the Panel control.

Member Description

Panel The main class for the control.

17) PlaceHolder Web Server Control Overview

The PlaceHolder control lets you place an empty container control in the page and then dynamically add child elements to it at run time.

Background

Page 32: Best Tutorial of c#

The PlaceHolder Web server control lets you place an empty container control within the page and then dynamically add, remove, or loop through child elements at run time. The control renders only its child elements; it renders no markup of its own.

For example, you might want to have a variable number of buttons appear on a Web page, depending on options selected by users. That way, users are not confronted with potentially confusing choices that are either unavailable or not relevant to their individual needs. You can create the buttons dynamically and then add them as children of aPlaceHolder control.

Code Examples

How to: Add PlaceHolder Web Server Controls to a Web Forms Page

How to: Add Controls to an ASP.NET Web Page Programmatically

Class Reference

The following table lists the classes that relate to the PlaceHolder control.

Member Description

PlaceHolder The main class for the control.

PlaceHolderControlBuilder The class that works with the parser to build a PlaceHolder control. To create a custom control builder for acontrol, you to inherit from this class.

18) RadioButton and RadioButtonList Web Server Controls Overview

The RadioButton control and the RadioButtonList control enable users to select from a small set of mutually exclusive, predefined choices.

Features

You can use the RadioButton control and the RadioButtonList control to:

Cause a page postback when a radio button is selected. Capture user interaction when a user selects a radio button. Bind each radio button to data from a database.

Background

You can use two types of Web server controls to add radio buttons to an ASP.NET Web page: individual RadioButton controls or a RadioButtonList control. Both controls enable users to select from a small set of mutually exclusive, predefined choices. The controls enable you to

Page 33: Best Tutorial of c#

define any number of radio buttons with labels and to arrange them horizontally or vertically.

You add individual RadioButton controls to a page and work with them singly. Typically, you group two or more individual buttons together. For more information, see Adding Individual RadioButton Controls to a Web Forms Page.

Alternatively, you can use the RadioButtonList control, which is a single control that acts as a parent control for a collection of radio button list items. It derives from the baseListControl class. Therefore, it works much like the ListBox, DropDownList, BulletedList, and CheckBoxList Web server controls. Many of the procedures for working with theRadioButtonList control are the same as they are for the other list Web server controls.

Both types of control have advantages. By using individual RadioButton controls, you get more control over the layout of the radio button group than by using the RadioButtonListcontrol. For example, you can include non-radio-button text between radio buttons.

The RadioButtonList control is a better choice if you want to create a group of radio buttons based on data in a data source. It is also slightly easier to write code that determines which button has been selected.

Note

You can also use the HtmlInputRadioButton server control to add radio buttons to an ASP.NET Web page. For more information, seeServer Control Declarative Syntax.

If you want to present users with a longer list of options or a list that might vary in length at run time, use a ListBox or DropDownList Web server control.

Grouping Radio Buttons

Radio buttons are rarely used singly. Instead, they are grouped to provide a set of mutually exclusive options. Within a group, only one radio button can be selected at a time. You can create grouped radio buttons in these ways:

Add individual RadioButton Web server controls to a page and then manually assign them all to a group. The group name is arbitrary; all radio buttons with the same group name are considered part of a single group.

Add a RadioButtonList Web server control to the page. The list items in the control are automatically grouped.

RadioButton and RadioButtonList Events

Events work differently between individual RadioButton controls and the RadioButtonList control.

Page 34: Best Tutorial of c#

Individual RadioButton Controls

Individual RadioButton controls raise the CheckedChanged event when users click the control. (This event is inherited from the CheckBox control.) By default, this event does not cause the page to be posted to the server. However, you can force the control to perform an immediate postback by setting the AutoPostBack property to true. For details about responding to this event directly, see How to: Respond to a User Selection in a RadioButton Web Server Control Group.

Note

The auto-postback capability requires that the browser support ECMAScript (JScript, or JavaScript) and that scripting be enabled on the user's browser.

You might need to create an event handler for the CheckedChanged event. You can test which radio button is selected in any code that runs as part of the page. Typically, you create an event handler for the CheckedChanged event only if you need to know that a radio button was changed, not just to read the current selection. For details, see How to: Set and Get the Selection in a RadioButton Web Server Control.

RadioButtonList Control

The RadioButtonList control raises a SelectedIndexChanged event when users change which radio button in the list is selected. By default, the event does not cause the page to be posted to the server. However, you can force the control to perform an immediate postback by setting the AutoPostBack property to true. For details, see How to: Respond to Changes in List Web Server Controls.

Note

The auto-postback capability requires that the browser support ECMAScript (JScript, or JavaScript) and that scripting be enabled on the user's browser.

As with individual RadioButton controls, it is more common to test the state of the RadioButtonList control after the page has been posted some other way. For details, see How to: Determine the Selection in List Web Server Controls.

RadioButton Control HTML Attributes

When the RadioButton control renders to the browser, it does so in two parts: an input element that represents the radio button, and a separate label element that represents the caption for the radio button. The combination of the two elements is wrapped in a span element.

When you apply style or attribute settings to a RadioButton control, they are applied to the outer span element. For example, if you set the control's BackColor property, the setting is applied to the span element. Therefore, it affects both the inner input and label elements.

At times, you might want to make separate settings for the radio button and the label. The RadioButton control supports two properties that you can set at run time.

Page 35: Best Tutorial of c#

TheInputAttributes property lets you add HTML attributes to the input element, and the LabelAttributes property lets you add HTML attributes to the label element. The attributes that you set are passed through as-is to the browser. The following example shows how to set attributes for the input element so that just the radio button, but not the label, changes color when users pass the mouse pointer over it.

C#

RadioButton1.InputAttributes.Add("onmouseover", "this.style.backgroundColor = 'red'");RadioButton1.InputAttributes.Add("onmouseout", "this.style.backgroundColor = 'white'");

Binding Data to the Control

You can bind an individual RadioButton control to a data source, and you can bind any property of the RadioButton control to any field of the data source. For example, you might set the control's Text property based on information in a database.

Because radio buttons are used in groups, binding a single radio button to a data source is not a common scenario. Instead, it is more typical to bind a RadioButtonList control to a data source. In that case, the data source dynamically generates radio buttons (list items) for each record in the data source.

Code Examples

How to: Add RadioButton Web Server Controls to a Web Forms Page

How to: Add RadioButtonList Web Server Controls to a Web Forms Page

How to: Set and Get the Selection in a RadioButton Web Server Control

How to: Set Layout in a RadioButtonList Web Server Control

How to: Respond to a User Selection in a RadioButton Web Server Control Group

How to: Add Items in List Web Server Controls

How to: Populate List Web Server Controls from a Data Source

How to: Respond to Changes in List Web Server Controls

Class Reference

The following table lists the classes that relate to the RadioButton and RadioButtonList controls.

Member Description

Page 36: Best Tutorial of c#

RadioButton The main class for the RadioButton control.

RadioButtonList The main class for the RadioButtonList control.

ListItem The class that represents each item in RadioButtonList control.

Items The collection of items that correspond to individual items in the list for a RadioButtonList

19) Substitution Web Server Control Overview

The Substitution control lets you create areas on the page that can be updated dynamically and then integrated into a cached page.

Scenarios

Use the Substitution control to specify a section of an output-cached Web page where you want to display dynamic content. The Substitution control offers a simplified solution to partial page caching for pages where the majority of the content is cached. You can output-cache the entire page, and then use Substitution controls to specify the parts of the page that are exempt from caching. Cached regions execute only once and are read from the cache until the cache entry expires or is purged. Dynamic regions execute every time that the page is requested. This caching model simplifies the code for pages that are primarily static, because you do not have to encapsulate the sections to cache in Web user controls. For example, this caching model is useful in a scenario where you have a page that contains static content, such as news stories, and an AdRotator control that displays advertisements. The news stories do not change frequently, which means that they can be cached. However, every time that a user requests the page, you want to display a new advertisement. The AdRotator control directly supports post-cache substitution and renders a new advertisement every time that the page posts back, regardless of whether the page is cached.

Background

When an ASP.NET page is cached, by default the entire output of the page is cached. On the first request, the page runs and caches its output. On subsequent requests, the request is fulfilled from the cache and code on the page does not run.

In some circumstances, you might want to cache an ASP.NET page but update selected portions of the page on every request. For example, you might want to cache the majority of a page but be able to dynamically update time-sensitive information on the page.

You can use the Substitution control to insert dynamic content into the cached page. The Substitution control does not render any markup. Instead, you bind the control to a method on the page or on a parent user control. You create a static method that returns the information that you want to insert into the page. The method called by theSubstitution control must meet the following criteria:

Page 37: Best Tutorial of c#

It must be a static method (shared in Visual Basic). It must accept a parameter of type HttpContext. It must return a value of type String.

Other controls on the page are not accessible to the Substitution control—that is, you cannot examine or change the value of other controls. However, the code does have access to the current page context by using the parameter passed to it.

When the page runs, the Substitution control calls the method and then substitutes the return value from the method for the Substitution control on the page.

Code Examples

The following example shows how to use the Substitution control to create dynamically updated content on a cached page. Code in the page's Load event updates a Label control with the current time. Because the page's cache duration is set to 60 seconds, the text of the Label control does not change even if the page is requested multiple times during the 60-second period. A Substitution control on the page calls the static method GetTime, which returns the current time as a string. Every time that the page is refreshed, the value represented by the Substitution control is updated.

C#<%@ Page Language="C#" %><%@ OutputCache Duration=60 VaryByParam="None" %>

<script runat="server"> void Page_Load() { Label1.Text = DateTime.Now.ToString(); } public static String GetTime(HttpContext context) { return DateTime.Now.ToString(); }</script><html><head runat="server"></head><body> <form id="form1" runat="server"> <div> <p> <asp:Label runat="server" ID="Label1" /> </p> <p> <asp:Substitution runat="server" ID="Substitution1" MethodName="GetTime" /> </p> <p> <asp:Button runat="server" ID="Button1" Text="Submit"/> </p> </div>

Page 38: Best Tutorial of c#

</form></body></html>

Class Reference

The following table lists the classes that relate to the Substitution control.

Member Description

Substitution The main class for the control.

20) Table, TableRow, and TableCell Web Server Control Overview

The Table Web server control enables you to create tables on ASP.NET pages that you can program in server code. The TableRow and TableCell Web server controls provide a way to display the content for the Table control.

Background

Tables are typically used not only to present tabular information, but as a way to format information on a Web page. There are a number of ways to create tables on ASP.NET pages:

HTML table. If you are creating a static table (one in which you will not add or change content at run time), you should use an HTML table and not a Table control.

HtmlTable control. This is a table HTML element that has been converted to an HTML server control by adding the runat=server attribute. You can program this control in server code. For details about HTML server controls, see ASP.NET Web Server Controls Overview.

Table. This is a Web control that enables you to create and manipulate tables (for example, adding table rows and cells) by using an object model that is consistent with other Web controls.

In general, you use a Table Web server control when you intend to add rows and cells (columns) to the table in code at run time. Although you can use it as a static table with predefined rows and columns, it is easier in that case to work with the HTML table element.

The Table Web server control can be easier to program than the HtmlTable control because it offers an object model with typed properties that is consistent with other Web server controls. (The model is also consistent between the Table, TableRow, and TableCell controls.)

Comparing the Table Web Server Control to Other List Web Server Controls

Page 39: Best Tutorial of c#

Some of the functions you might accomplish with a Table Web server control can also be accomplished with the list Web server controls, specifically the Repeater, DataList, andGridView controls. All these controls are rendered (or have the option to be rendered) as HTML tables.

The differences between the list controls and the Table control are these:

The list controls are data-bound. The list controls work only against a data source, whereas the Table control can display any combination of HTML text and controls, whether or not they are data-bound.

The list controls use templates to specify the layout of their elements. The Table control supports the TableCell child control, which you can fill as you would any HTML tdelement.

Table Web Server Control Object Model

The Table control acts as a parent control for TableRow controls. The table supports a property named Rows that is a collection of TableRow objects. By adding or deleting items in this collection, you specify the rows for the table. The TableRow control in turn supports a collection named Cells that contains TableCell objects.

The content to be displayed in the table is added to the TableCell control. The cell has a Text property that you set to any HTML text. Alternatively, you can display controls in the cell by adding controls to the cell's Controls collection.

The parent Table control supports properties to control the appearance of the entire table, such as Font, BackColor, and ForeColor. The TableRow and TableCell controls support these properties as well, so you can specify the look of individual rows or cells, overriding the parent table appearance.

Binding Data to the Control

Although the Table control is not inherently data-bound, you can use it to display data from a database. As with all Web server controls, you can bind any property of a Tablecontrol to a data source. However, the Table control does not support a property that you use to directly display data. Instead, you typically add TableCell controls to the table. You can then either bind the Text property of individual TableCell controls to data, or you can add data-bound controls (such as a Label or Literal control) to the cell.

Code Examples

How to: Add Table Web Server Controls to a Web Forms Page

How to: Add Rows and Cells Dynamically to a Table Web Server Control

Class Reference

The following table lists the classes that relate to the Table control, the TableCell control, and the TableRow control.

Page 40: Best Tutorial of c#

Member Description

Table The main class for the Table control.

TableCell The main class for the TableCell control.

TableCellCollection Encapsulates a collection of TableHeaderCell and TableCell objects that make up a row in a

TableFooterRow Represents a footer row in a Table control.

TableHeaderCell Represents a heading cell within a Table control.

TableHeaderRow Represents a heading row in a Table control.

TableHeaderScope Represents the HTML scope attribute for classes that represent header cells in a table.

TableItemStyle Represents the style properties for an element of a control that renders as a TableRow

TableRow The main class for the TableRow control.

TableRowCollection Encapsulates a collection of TableRow objects that represent a single row in a Table

TableRowSection Specifies where a TableRow object is placed in a Table control.

TableSectionStyle Represents the style for a section of a Table control.

TableStyle Represents the style for the Table control.

21) TextBox Web Server Control Overview

The TextBox Web server control provides a way for users to type information into an ASP.NET Web page, including text, numbers, and dates.

Background

The TextBox server control is an input control that lets the user enter text. By default, the TextMode property of the control is set to TextBoxMode.SingleLine, which displays a single-line text box. However, you can set the TextMode property to TextBoxMode.MultiLine to display a multi-line text box (which renders as a textarea element). You can also change the TextMode property to TextBoxMode.Password to display a text box that masks user input. The text displayed in the TextBox control is available by using the Textproperty.

Security NoteSetting the TextMode property to TextBoxMode.Password can help make sure that other people cannot see a password as it is being entered. However, the text entered into the text box is not encrypted in any way, and you should protect it as you would any other confidential data. For example, for increased security when posting a page with a password in it, you can use Secure Sockets Layer (SSL) and encryption.

Page 41: Best Tutorial of c#

Security NoteUser input in an ASP.NET Web page can include potentially malicious client script. By default, the ASP.NET Web page validates that user input does not include script or HTML elements. For more information, see Script Exploits Overview.

TextBox Events

The TextBox control raises a TextChanged event when the user leaves the control. By default, the event is not raised immediately; instead, it is raised on the server when the page is submitted. However, you can specify that the TextBox control should submit the page to the server as soon as the user leaves the field.

The TextBox Web server control does not raise an event each time the user enters a keystroke, only when the user leaves the control. You can have the TextBox control raise client-side events that you handle in client script, which can be useful for responding to individual keystrokes. For details, see Client Script in ASP.NET Web Pages.

TextBox Captions

You can use Label controls to create captions for TextBox controls. The caption can define an access key that users can press to navigate to the TextBox control. For details, seeHow to: Use Label Web Server Controls as Captions.

Auto-Completion in Text Boxes

Many browsers support an auto-completion feature that helps users fill information into text boxes based on values that the users have entered previously. The exact behavior of auto-completion depends on the browser. In general, browsers store values based on the text box's name attribute; any text box with the same name, even on a different page, will offer the same values to the user. Some browsers also support a vCard schema, which allows users to create a profile in the browser with predefined values for first name, last name, telephone number, e-mail address, and so on.

The TextBox control supports an AutoCompleteType property that provides you with these options for controlling how the browser works with auto-completion:

Disable auto-completion. If you do not want the browser to offer auto-completion for a text box, you can disable it.

Specify a vCard value to use as the auto-completion value for the field. The browser must support the vCard schema.

Code Examples

How to: Get and Set Values in TextBox Web Server Controls

How to: Respond to Changes in a TextBox Web Server Control

How to: Set a TextBox Web Server Control for Password Entry

How to: Specify Multiline Input for a TextBox Web Server Control

Page 42: Best Tutorial of c#

Class Reference

The following table lists the classes that relate to the BulletedList control.

Member Description

TextBox The main class for the control.

TextBoxMode Specifies whether the TextBox control is in single-line, multi-line, or password mode.

22) Wizard Web Server Control Overview

Use the Wizard control to simplify many of the tasks that are associated with building a series of forms to collect user input.

Scenarios

Collecting user input by using forms is a recurring task in Web development. A group of forms that is used to accomplish a task is often called a wizard.

The ASP.NET Wizard control simplifies many of the tasks that are associated with building multiple forms and collecting user input. The Wizard control provides a simple mechanism that allows you to easily build steps, add a new step, or reorder the steps. You can build linear and non-linear navigation and customize the control's user navigation without writing code.

Background

Building a series of interconnected forms to break up data collection is a common practice. You can accomplish this by managing the navigation between forms, the data persistence, and the state management in each step. With the Wizard control, you use discrete steps to collect data, which allows users to navigate between steps at their discretion and creates a simpler user experience. As a developer, you do not have to worry about making your data persist across pages because the control maintains state while the user completes the various steps.

Wizard Steps

The Wizard control uses steps to delineate different sections of user data input. Each step within the control is given a StepType to indicate whether it is the beginning step, intermediate step, or completion step. The wizard can have as many intermediate steps as needed. You can add different controls, such as a TextBox or ListBox control, to collect user input. When you reach the Complete step, all of your data is accessible. The following code example illustrates the Wizard control with two steps.

Page 43: Best Tutorial of c#

Copy<asp:Wizard ID="Wizard1" Runat="server"> <WizardSteps> <asp:WizardStep Runat="server" Title="Step 1"> </asp:WizardStep> <asp:WizardStep Runat="server" Title="Step 2"> </asp:WizardStep> </WizardSteps></asp:Wizard>

Within each step, you can add controls and labels, and accept user data. The Wizard control will help manage which step to display, and help maintain the collected data.

Wizard Navigation

The Wizard control features both linear and non-linear navigation. The control's state management allows the user to move forward and backward between steps, and it allows the user to select individual steps at any point, as long as the sidebar is displayed. You can customize the text for navigation in the control's root asp:Wizard element by using theStepNextButtonText, StepPreviousButtonText, and FinishCompleteButtonText properties.

Copy<asp:Wizard ID="Wizard1" Runat="server" StepNextButtonText=" Next >> " StepPreviousButtonText=" << Previous " FinishCompleteButtonText=" Done! ">

Customizing Other Wizard Control Aspects

The Wizard control automatically displays a title and the control's current step. The title is customized with the HeaderText property. You can adjust the header's template by using the HeaderTemplate property.

You can optionally display a cancel button by setting the DisplayCancelButton property to true.

The Wizard control's NavigationButtonStyle property provides an easy way to set all of the buttons to a common style, while providing the flexibility to customize each button individually. The NavigationButtonStyle property applies to all of the buttons rendered. However, you can override this style by setting the individual button's style property.

Navigation Templates

The Wizard control supports templates that allow you to further customize the interface of the control with the StartNavigationTemplate, FinishNavigationTemplate,StepNavigationTemplate, and SideBarTemplate properties.

Wizard Control Events

Page 44: Best Tutorial of c#

You can customize the behavior of the Wizard control by using custom code and events.

For example, you can intercept the NextButtonClick event, which is raised when the user clicks the Next button and captures the data of the current step. TheWizardNavigationEventArgs parameter passed to this event includes the CurrentStepIndex and NextStepIndex properties, enabling you to customize the behavior of the control based on the current and next steps, or to cancel the navigation when the Next button is clicked.

Similarly, you can customize the behavior of the Previous and Finish buttons by using the PreviousButtonClick and FinishButtonClick events. Or you can perform cleanup when theCancel button is clicked by using the CancelButtonClick event.

Formatting and CSS Styles

By default, the Wizard control layout is rendered using an HTML table. However, using tables to lay out visual elements on a page is not semantically correct and might not be compatible with cascading style sheet (CSS) rules. To address this issue, the Wizard control can render markup that uses CSS for layout instead of using tables. This makes it easier to format the control. The Wizard control supports a LayoutTemplate property that you can use to specify the layout of visual elements. For more information, seeLayoutTemplate.

The Wizard control also supports the ability to use a ListView control instead of a DataList control inside its sidebar area. For more information, see SideBarTemplate.

Code Examples

Walkthrough: Creating a Basic ASP.NET Wizard Control

Walkthrough: Advanced Use of the ASP.NET Wizard Control

Class Reference

The following table lists the key classes that relate to the Wizard control.

Member Description

Wizard The main class for the control.

WizardNavigationEventArgs Provides the data that is needed for the various navigation events in a Wizard

WizardNavigationEventHandler Represents the method that will handle navigation events in a Wizard control.

WizardStep Represents a basic step that is displayed in a Wizard control.

WizardStepCollection Represents a collection of WizardStep objects that contain the user interface for each step, as defined by the page developer.

WizardStepType Specifies the types of navigation UI that can be displayed for a step in a Wizard

Page 45: Best Tutorial of c#

23) XML Web Server Control Overview

You can use the Xml Web server control to display the contents of an XML document without formatting or by using XSL transformations.

Scenarios

An Xml Web server control reads XML and writes it into an ASP.NET Web page at the location of the control. If an XSL transformation (XSLT) is applied to the XML, the resulting transformed output will be rendered in the page.

Background

You can use the XML Web server control to write an XML document, or the results of an XSLT transformation, into an ASP.ENT Web page. The XML output appears in the Web page at the location of the control.

NoteTo use XML data as the source for other controls, such as the Repeater, DataList, or GridView controls, you can use theseeXmlDataSource Web Server Control Overview.

The XML and the XSLT information can be in external documents, or you can include the XML inline. There are two ways to reference external documents using property settings in the XML Web server control. You can provide a path to the XML document in the control tag, or you can programmatically load the XML and XSLT documents as objects and then pass them to the control. If you prefer to include the XML inline, write it between the opening and closing tags of the control.

The XML document to display is specified by setting one of properties listed in the following table. These three properties represent the different types of XML documents that can be displayed. You can display a System.Xml.XmlDocument, an XML string, or an XML file by setting the appropriate property.

Property Description

Document Sets the XML document by using a System.Xml.XmlDocument object.

DocumentContent Sets the XML document by using a string.

NoteThis property is typically set declaratively by placing text between the opening and closing

DocumentSource Sets the XML document by using a file.

At least one of the XML document properties must be set to display an XML document. If more than one XML document property is set, the XML document referenced in the last property set is displayed. The documents in the other properties are ignored.

Page 46: Best Tutorial of c#

You can optionally set properties to specify an XSL Transformation (XSLT) style sheet that formats the XML document before it is written to the output stream. The properties represent the different types of XSL transformation style sheets that can be used to format the an document. You can format the XML document with aSystem.Xml.Xsl.XslCompiledTransform object or with an XSL transformation style sheet file by setting the appropriate property. If no XSL transformation style sheet is specified, the XML document is displayed by using the default format.

Code Examples

Walkthrough: Displaying an XML Document in a Web Forms Page Using Transformations

How to: Add XML Web Server Controls to a Web Forms Page

How to: Load XML Data in the XML Web Server Control

How to: Transform XML Data in the XML Web Server Control

Class Reference

The following table lists the classes that relate to the XML control.

Member Description

XML The main class for the control.

24) Securing Standard Controls

The ASP.NET standard controls are a group of controls that enable you to create forms in which users can type or select information before a page is posted back to the server. Standard controls are Web server controls that inherit from the Control class. Examples of Web server controls include the TextBox, Image, and AdRotator controls. The information in this topic describes configuration and coding best practices that will help you improve the security of standard controls.

While following coding and configuration best practices can help improve the security of your application, it is also important that you continually keep your application server up to date with the latest security updates for Microsoft Windows and Internet Information Services (IIS), as well as any security updates for Microsoft SQL Server or other data sources.

More detailed information about best practices for writing secure code and securing applications can be found in the book "Writing Secure Code" by Michael Howard and David LeBlanc, or through the guidance provided by Microsoft Patterns and Practices.

Information about special security practices for other types of controls is also available in the following topics:

Page 47: Best Tutorial of c#

Securing Login Controls Securing Web Parts Pages Securing Data Access

AdRotator Control

The AdRotator control displays advertisements defined in an advertisement file, which by default is an XML file. Alternatively, you can store advertisements in a database and extract them programmatically. To help secure the AdRotator control, follow these guidelines:

If you are using an XML file to store advertisement information, place the file in the Web site's App_Data folder, because the contents of the folder will not be served in response to Web requests.

For extra protection, do not use the .xml file name extension on advertisement files. Instead, use an extension such as .ads, and then map the .ads extension to ASP.NET in IIS and to the forbidden handler in ASP.NET using the following element in the site's Web.config file:

Copy

<httpHandlers> <add verb="*" path="*.ads" type="System.Web.HttpForbiddenHandler" /></httpHandlers>

For information on how to map a file name extension to ASP.NET in IIS, see How to: Register HTTP Handlers.

Set appropriate permissions (typically read-only) for the user account or accounts that will be reading the advertisement file. If the Web site supports anonymous access, this is usually the local ASPNET user account or the NETWORK SERVICE account.

If the advertisement file does not exist, the AdRotator control raises an error that displays the path and name of the file, which reveals potentially sensitive information. Avoid this problem by following proper error-handling techniques, including setting the customErrors element in the configuration file to redirect to a custom error page and creating a global error handler that is called if an unhandled exception occurs anywhere in the application. For details, see How to: Display Safe Error Messages.

If you are reading advertisement information from a database, follow the guidelines for securing access to the database. For details, see Securing Data Access.

Carefully examine any advertisement information that you get from an untrusted source before using it with the AdRotator control. Because the AdRotator control does not perform any validation or check the information it reads from the advertisement file, it renders images and URLs to the Web page exactly as they appear in the ad file or database.

BulletedList, CheckBoxList, RadioButtonList, DropDownList, ListBox

Page 48: Best Tutorial of c#

The BulletedList, CheckBoxList, DropDownList, ListBox, and RadioButtonList controls render different types of HTML elements (ul, input, and select) based on the contents of collections or on data in a database. To help secure these controls, follow these guidelines:

If the controls read from a database, follow the guidelines for securing access to the database. For details, see Securing Data Access.

If you are unsure whether the information to be displayed contains script or other markup, handle the control's DataBinding event and HTML-encode the information before displaying it. For details, see How to: Protect Against Script Exploits in a Web Application by Applying HTML Encoding to Strings.

If the BulletedList control is configured to display graphics or hyperlinks, make sure that the URL for the graphic or link points to a trusted location.

Calendar Control

The Calendar control renders LinkButton controls to enable navigation in the calendar. LinkButton controls use client script to perform a postback. If a browser has turned off client script for security purposes, the Calendar control will not support navigation.

You can always use the Calendar control to display dates, even if you are not using it to enable date navigation. Do not assume that any selected dates in a Calendar control are formatted correctly. When converting dates from the Calendar control to an internal DateTime format, be sure to use appropriate error handling in case the date is not in the correct format.

FileUpload Control

The FileUpload control enables users to upload a file from their computer to the Web server computer. To help secure the FileUpload control, follow these guidelines:

Do not trust files that are uploaded by users; malicious users might try to upload executable files. When you save an uploaded file, check its file name extension or assign your own extension to the file.

Do not allow users to specify an arbitrary path for the location to save the uploaded file. Check that the name of the file does not contain path information that you have not added yourself.

Do not reveal the internal structure of your Web site to users who are uploading files. Set read/write permissions for the user account or accounts that will be running the

application on the folder or folders where the uploaded files will be saved. If the Web site supports anonymous access, this is generally the local ASPNET user account or the NETWORK SERVICE account. However, limit read/write permissions to only the folder or folders where the application stores uploaded files.

Guard against denial-of-service attacks by setting the maxRequestLength attribute of the httpRuntime element in the configuration file. By default, the maximum request length is 4 megabytes (MB). Other configuration settings that can affect the size of uploaded files are the requestLengthDiskThreshold attribute of the httpRuntime element and the memoryLimit attribute of the processModel element.

Determine the size of the uploaded file by querying the ContentLength property of the HttpPostedFile object returned by the control, and use the size to decide whether to accept the file.

Page 49: Best Tutorial of c#

HiddenField Control

The HiddenField control provides you with a way to set the contents of HTML <input type="hidden"> elements in server code. Hidden fields are used to store information in the page that is useful during page processing but should not be seen by users. To help secure the HiddenField control, follow these guidelines:

Do not store sensitive information in HiddenField controls. Although the information is not visible in the browser, it is part of the page and users can easily view it in the page's source.

Do not trust information in hidden fields. Malicious users can tamper with the content of hidden fields.

Hyperlink

The HyperLink control renders a URL to the browser. Be sure that the URL points to a trusted location.

Image and ImageMap Controls

To display graphics, the Image and ImageMap controls render a URL to the browser. Be sure that the URL points to a trusted location.

ImageButton Control

The ImageButton control renders an image (img element) that uses client script to perform a postback. If a browser has turned off client script for security purposes, the control will not function.

To display the graphic, the control renders a URL to the browser. Be sure that the URL points to a trusted location.

Label and Literal Controls

The Label and Literal controls display text on the page by passing it through to the browser as-is. (The Label control additionally enables you to specify formatting.) If the text contains HTML markup, by default the browser will interpret the markup and render the text accordingly, which might include running scripts.

If you are using the Label control and are unsure whether the text might contain malicious content, use HTML encoding to convert the HTML to its text representation. For details, see How to: Protect Against Script Exploits in a Web Application by Applying HTML Encoding to Strings.

If you are using the Literal control and are unsure whether the text might contain malicious content, do one of the following:

Set the control's LiteralMode property to Encode, which automatically encodes HTML content.

Page 50: Best Tutorial of c#

Use HTML encoding to convert the HTML to its text representation. For details, see How to: Protect Against Script Exploits in a Web Application by Applying HTML Encoding to Strings.

For more information, see How to: Protect Against Script Exploits in a Web Application by Applying HTML Encoding to Strings.

LinkButton Control

The LinkButton control renders a link (a element) that uses client script to perform a postback. If a browser has turned off client script for security purposes, the control will not function.

MultiView

The MultiView control enables you to add multiple View controls and display them conditionally. This gives you the ability to create pages that look like multi-page forms.

If you switch views based on something that can be easily tampered with, such as a URL query string, you could enable someone to see a view that they are not supposed to see. Therefore, be sure that the mechanisms for switching views are as secure as possible. For more information, see ASP.NET State Management Overview.

TextBox Control

Because the TextBox control allows users to enter almost any text into the page, you must be careful when accepting user input with this control. To help secure the TextBoxcontrol, follow these guidelines:

Use validation controls whenever possible to limit the users' input to acceptable values. For details, see Introduction to the Validation Controls.

Ensure that the IsValid property is set to true before running your server code. Use redundant server validation. This is especially true for CustomValidator controls;

do not create only client-side validation logic. Set the TextBox control's MaxLength property to limit the quantity of text that users

can enter. Malicious users can affect the performance of your application and potentially cause database errors by sending huge quantities of information in a text box.

Encode user input with the HtmlEncode method, which turns HTML into its text representation (for example, <b> becomes &ltb&gt;), and which helps prevent the HTML from being executed in a browser. For details, see How to: Protect Against Script Exploits in a Web Application by Applying HTML Encoding to Strings.

Set the TextMode property to Password to prevent the contents of the text box from being viewed in the text box (by displaying dots). Note that setting the TextModeproperty to Password provides no other protection; the contents of the text box are not encrypted or otherwise obfuscated, and the information is sent to the server as clear text. Therefore, when using Password, provide additional methods for ensuring that data is secured.

If you are collecting sensitive information, such as a password or credit card number, use Secure Sockets Layer (SSL) to secure communication between the client and

Page 51: Best Tutorial of c#

server. This applies to any use of TextBox controls, including controls that incorporate TextBox controls, such as the CreateUserWizard control.

Wizard

The Wizard control enables you to create multi-step entry forms. Be aware of the following security considerations when using the Wizard control:

The Wizard does not inherently protect sensitive information. If you are collecting sensitive data in the wizard, use SSL to secure communication between the client and server for the page containing the Wizard.

To support its functionality, the Wizard control includes a number of non-visible controls. A user can potentially manipulate those controls and their values to display wizard steps out of order or to display wizard steps that should be displayed to only some users. To help prevent this, ensure that wizard steps are displayed in the correct order, and that steps with sensitive information are not displayed unless the correct conditions apply.

XML Control

The Xml control displays the contents of an XML file or string containing XML on a page, optionally applying an XML transformation. To help secure the Xml control, follow these guidelines:

When you are displaying the contents of an XML file, if practical, place the XML file in the in your site's App_Data folder because the contents of the folder will not be served in response to Web requests.

Display XML only from trusted sources. Use transformations only from trusted sources.

Types of Validation for ASP.NET Server Controls

The following table lists ASP.NET validation controls and how you can use them.

Security Note

By default, ASP.NET Web pages automatically validate that malicious users are not attempting to send script to your application. For more information, see Script Exploits Overview.

Type of validation Control to use Description

Required entry RequiredFieldValidator Ensures that the user does not skip an entry. For details, seeRequired Entries for ASP.NET Server Controls

Comparison to a value CompareValidator Compares a user's entry against a constant value, against the value of another control (using a comparison operator such as less than, equal, or greater than), or for a specific data type. For details, see How to: Validate Against a Specific Value for

Page 52: Best Tutorial of c#

ASP.NET Server Controls and How to: Validate Against a Data Type for ASP.NET Server Controls.

Range checking RangeValidator Checks that a user's entry is between specified lower and upper boundaries. You can check ranges within pairs of numbers, alphabetic characters, and dates. For details, see How to: Validate Against a Range of Values for ASP.NET Server Controls

Pattern matching RegularExpressionValidator Checks that the entry matches a pattern defined by a regular expression. This type of validation enables you to check for predictable sequences of characters, such as those in e-mail addresses, telephone numbers, postal codes, and so on. For details, seeto: Validate Against Patterns for ASP.NET Server Controls

User-defined CustomValidator Checks the user's entry using validation logic that you write yourself. This type of validation enables you to check for values derived at run time. For details, seeto: Validate with a Custom Function for ASP.NET Server ControlsValidate Against Values in a Database for ASP.NET Server Controls

You can attach more than one validation control to an input control. For example, you might specify that a control is required and that it also contains a specific range of values.

A related control, the ValidationSummary control, does not perform validation, but is often used in conjunction with other validation controls to display the error messages from all the validation controls on the page together. For more information, see How to: Control Validation Error Message Display for ASP.NET Server Controls.

******ASP.NET Data-Bound Web Server Controls Overview

Data-bound Web server controls are controls that can be bound to a data source control to make it easy to display and modify data in your Web application. Data-bound Web server controls are composite controls that combine other ASP.NET Web controls, such as Label and TextBox controls, into a single layout.

For example, a data-bound control such as a DetailsView control can bind to a set of results such as a table of employees containing each employee's name, address, job title, and so on. Within the DetailsView control, you can bind Label controls to a single data values such as the name or address field to create the data layout in the page.

In addition to enabling you to bind the control to a set of data results, data-bound controls enable you to customize the layout of the control using templates. They also provide a convenient model for handling and canceling events.

Binding a Data-bound Web Server Control to Data

You can work with a data-bound control by binding it to a data source control such as an ObjectDataSource or SqlDataSource control. The data source control connects to a data source such as a database or middle-tier object and then retrieves or updates data. The

Page 53: Best Tutorial of c#

data-bound control can then use this data. To perform the binding, you set the data-bound control's DataSourceID property to point to a data source control. When a data-bound control is bound to a data source control, little or no additional code is required for data operations, because the data-bound control can automatically take advantage of the data services provided by the data source control.

NoteIn ASP.NET version 1.0 and version 1.1, data-bound controls were bound to data using the DataSource property and required you to write code to handle operations such as displaying, paging, sorting, editing, and deleting data. Although you can still bind controls to data by using theuse existing code), in ASP.NET version 2.0 and later you can perform binding by using the DataSourceID property instead.

For more information about data source controls, see Data Source Web Server Controls.

Using Data-bound Web Server Controls with ASP.NET Dynamic Data

Some ASP.NET data-bound controls are supported by ASP.NET Dynamic Data, including the DetailsView, FormView, GridView and ListView controls.

The IDataBoundControl, IDataBoundListControl, IDataBoundItemControl and the IFieldControl interfaces expose the common properties that are required for Dynamic Data support. If you are creating a custom data-bound control that will work with Dynamic Data, you can implement these interfaces instead of deriving from the DataBoundControlclass.

GridView Control

The GridView control displays data as a table and provides the capability to sort columns, page through data, and edit or delete a single record.

NoteThe GridView control is the successor to the DataGrid control available in earlier versions of ASP.NET. Along with the added ability to take advantage of the capabilities of data source controls, the GridView control offers improvements such as the ability to define multiple primary key fields, improved user interface customization using bound fields and templates, and a new model for handling or canceling events.

For more information, see GridView Web Server Control Overview and Comparing the GridView and DataGrid Web Server Controls.

DetailsView Control

The DetailsView control renders a single record at a time as a table and provides the capability to page through multiple records, as well as to insert, update, and delete records. The DetailsView control is often used in master-detail scenarios where the selected record in a master control such as a GridView control determines the record displayed by theDetailsView control.

Page 54: Best Tutorial of c#

For more information, see DetailsView Web Server Control Overview.

FormView Control

The FormView control renders a single record at a time from a data source and provides the capability to page through multiple records, as well as to insert, update, and delete records, similar to the DetailsView control. However, the difference between the FormView and the DetailsView controls is that the DetailsView control uses a table-based layout where each field of the data record is displayed as a row in the control. In contrast, the FormView control does not specify a pre-defined layout for displaying a record. Instead, you create templates that contain controls to display individual fields from the record. The template contains the formatting, controls, and binding expressions used to lay out the form. You can specify whether the FormView control renders content using tables by setting the RenderTable() property to true.

For more information, see FormView Web Server Control Overview.

Repeater Control

The Repeater control renders a read-only list from a set of records returned from a data source. Like the FormView control, the Repeater control does not specify a built-in layout. Instead you create the layout for the Repeater control using templates.

For more information, see Repeater Web Server Control Overview.

DataList Control

The DataList control renders data as table and enables you to display data records in different layouts, such as ordering them in columns or rows. You can configure the DataListcontrol to enable users to edit or delete a record in the table. (The DataList control does not take advantage of the capabilities of data source controls for modifying data; you must supply this code yourself.) The DataList control differs from the Repeater control in that the DataList control explicitly places items in an HTML table, where as the Repeatercontrol does not.

For more information, see DataList Web Server Control Overview.

ListView Control

The ListView control displays data from a data source in a format that you define using templates. The template contains the formatting, controls, and binding expressions that are used to lay out the data. The ListView control is useful for data in any repeating structure, similar to the DataList and Repeater controls. However, unlike the DataList andRepeater controls, the ListView control implicitly supports edit, insert, and delete operations, as well as sorting and paging functionality.

ListView Web Server Control Overview

Page 55: Best Tutorial of c#

The ASP.NET ListView control enables you to bind to data items that are returned from a data source and display them. You can display data in pages. You can display items individually, or you can group them.

The ListView control displays data in a format that you define by using templates and styles. It is useful for data in any repeating structure, similar to the DataList and Repeatercontrols. However, unlike those controls, with the ListView control you can enable users to edit, insert, and delete data, and to sort and page data, all without code.

Binding Data to the ListView Control

You can bind the ListView control to data in these ways:

By using the DataSourceID property. This enables you to bind the ListView control to a data source control, such as the SqlDataSource control. We recommend this approach because it enables the ListView control to take advantage of the capabilities of the data source control. It also provides built-in functionality for sorting, paging, inserting, deleting, and updating. This approach also enables you to use two-way binding expressions. For more information about data source controls, see Data Source Controls Overview.

By using the DataSource property. This enables you to bind to various objects, which includes ADO.NET datasets and data readers and in-memory structures such as collections. This approach requires that you write code for any additional functionality such as sorting, paging, and updating.

Creating Templates for the ListView Control

Items that are displayed by a ListView control can be defined by templates, similar to how templates are used in the DataList and Repeater controls. The ListView control lets you display data as individual items or in groups.

If you use layout templates, you can define the main (root) layout of a ListView control by creating a LayoutTemplate template. The LayoutTemplate must include a control that acts as a placeholder for the data. For example, the layout template might include an ASP.NET Table, Panel, or Label control. (It might also include HTML table, div, or span elements that have a runat attribute that is set to "server".) If you do not define a layout template, a placeholder control is automatically inserted. This placeholder control contains the output for each item as defined by the ItemTemplate template, which can be grouped in the content that is defined by the GroupTemplate template.

You define content for individual items in the ItemTemplate template. This template typically contains controls that are data-bound to data columns or other individual data elements.

Grouping Items

You can optionally group items in a ListView control by using the GroupTemplate template. You typically group items to create a tiled table layout. In a tiled table layout, the items are repeated in a row the number of times specified in the GroupItemCount property.

Note

Page 56: Best Tutorial of c#

If no layout is defined, if you set the GroupItemCount property to a value greater than zero, and if you also define anfunctions as if theLayoutTemplate property were defined. If you define a LayoutTemplate property, a PlaceHolder

In order to create a tiled table layout, the layout template might contain an ASP.NET Table control or an HTML table element that has a runat attribute set to "server". The group template can then contain an ASP.NET TableRow control (or an HTML tr element). The item template can contain individual controls that are inside an ASP.NET TableCell control (or an HTML td element).

You can use the EditItemTemplate template to supply data-bound UI that enables users to modify existing data items. You can use the InsertItemTemplate template to define data-bound UI that enables users to add a new data item. For more information, see Modifying Data later in this topic.

Available Templates

The following table lists all the templates that are used with the ListView control.

LayoutTemplate

Identifies the root template that defines the main layout of the control. It contains a placeholder object, such as a table row (tr), div, or span element. This element will be replaced with the content that is defined in the ItemTemplate template or in the GroupTemplate template. It might also contain a DataPager object.

ItemTemplate

Identifies the data-bound content to display for single items.

ItemSeparatorTemplate

Identifies the content to render between single items.

GroupTemplate

Identifies the content for the group layout. It contains a placeholder object, such as a table cell (td), div, or span that will be replaced with the content defined in the other templates, such as the ItemTemplate and EmptyItemTemplate templates.

GroupSeparatorTemplate

Identifies the content to render between groups of items.

EmptyItemTemplate

Identifies the content to render for an empty item when a GroupTemplate template is used. For example, if the GroupItemCount property is set to 5, and the total number of items returned from the data source is 8, the last row of data displayed by the ListView control will contain three items as specified by the ItemTemplate template, and two items as specified by the EmptyItemTemplate template.

Page 57: Best Tutorial of c#

EmptyDataTemplate

Identifies the content to render if the data source returns no data.

SelectedItemTemplate

Identifies the content to render for the selected data item to differentiate the selected item from the other displayed items.

AlternatingItemTemplate

Identifies the content to render for alternating items to make it easier to distinguish between consecutive items.

EditItemTemplate

Identifies the content to render when an item is being edited. The EditItemTemplate template is rendered in place of the ItemTemplate template for the data item being edited.

InsertItemTemplate

Identifies the content to render when an item is being inserted. The InsertItemTemplate template is rendered in place of an ItemTemplate template at either the start of the items displayed by the ListView control, or at the end. You can specify where the InsertItemTemplate template is rendered by using the InsertItemPosition property of theListView control.

Paging Data

To enable users to page through data in a ListView control, you can use a DataPager control. The DataPager control can be inside the LayoutTemplate template or on the page outside the ListView control. If the DataPager control is not in the ListView control, you must set the PagedControlID property to the ID of the ListView control.

The DataPager control supports built-in paging UI. You can use the NumericPagerField object, which enables users to select a page of data by page number. You can also use theNextPreviousPagerField object. This enables users to move through pages of data one page at a time, or to jump to the first or last page of data.

By default, if a user selects a row on a page, the same row is selected on each page. If you want to persist selection only for the row that the user has selected (as identified by the row's data key), you can set the EnablePersistedSelection property to true.

The size of the pages of data is set by using the PageSize property of the DataPager control. You can use one or more pager field objects in a single DataPager control.

You can also create custom paging UI by using the TemplatePagerField object. In the TemplatePagerField template, you can reference the DataPager control by using

Page 58: Best Tutorial of c#

theContainer property. This property provides access to the properties of the DataPager control. These properties include the starting row index, the page size, and the total number of rows currently bound to the ListView control.

The following example shows a DataPager class that is included in the LayoutTemplate template of a ListView control.

Copy<asp:ListView runat="server" ID="ListView1" DataSourceID="SqlDataSource1"> <LayoutTemplate> <table runat="server" id=" table1"> <tr runat="server" id="itemPlaceholder"> </tr> </table> <asp:DataPager runat="server" ID="DataPager" PageSize="5"> <Fields> <asp:NumericPagerField ButtonCount="10" PreviousPageText="<--" NextPageText="-->" /> </Fields> </asp:DataPager> </LayoutTemplate> <ItemTemplate> <tr runat="server"> <%-- Data-bound content. --%> </tr> </ItemTemplate></asp:ListView>

The following illustration shows a layout that displays links to pages of data based on the page number, using the NumericPagerField object.

The following example shows how to create the layout.

Copy<asp:DataPager runat="server" ID="DataPager" PageSize="10"> <Fields>

Page 59: Best Tutorial of c#

<asp:NumericPagerField ButtonCount="10" CurrentPageLabelCssClass="CurrentPage" NumericButtonCssClass="PageNumbers" NextPreviousButtonCssClass="PageNumbers" NextPageText=" > " PreviousPageText=" < " /> </Fields></asp:DataPager>

The following illustration shows paging UI that displays links to the next, previous, first, and last pages of data by using the NextPreviousPagerField object. The paging UI also includes custom content from a TemplatePagerField template, which displays the current item number range and the total number of items. The TemplatePagerField template includes a text box where users can enter the number of an item to move to. The specified item is displayed as the first item on the page.

The following example shows how to create the paging UI.

Copy<asp:DataPager runat="server" ID="EmployeesDataPager" PageSize="8"> <Fields> <asp:TemplatePagerField> <PagerTemplate> &nbsp; <asp:TextBox ID="CurrentRowTextBox" runat="server" AutoPostBack="true" Text="<%# Container.StartRowIndex + 1%>" Columns="1" style="text-align:right" OnTextChanged="CurrentRowTextBox_OnTextChanged" /> to <asp:Label ID="PageSizeLabel" runat="server" Font-Bold="true" Text="<%# Container.StartRowIndex + Container.PageSize > Container.TotalRowCount ? Container.TotalRowCount : Container.StartRowIndex + Container.PageSize %>" /> of <asp:Label ID="TotalRowsLabel" runat="server" Font-Bold="true" Text="<%# Container.TotalRowCount %>" />

Page 60: Best Tutorial of c#

</PagerTemplate> </asp:TemplatePagerField> <asp:NextPreviousPagerField ShowFirstPageButton="true" ShowLastPageButton="true" FirstPageText="|<< " LastPageText=" >>|" NextPageText=" > " PreviousPageText=" < " /> </Fields></asp:DataPager>

The following example shows the event handler for the TextChanged event of the TextBox control that is included in the TemplatePagerField template. The code in the handler moves to the data item that is specified by the user.

VBC#C++F#JScriptCopyprotected void CurrentRowTextBox_OnTextChanged(object sender, EventArgs e){ TextBox t = (TextBox)sender; DataPager pager = (DataPager)EmployeesListView.FindControl("EmployeesDataPager"); pager.SetPageProperties(Convert.ToInt32(t.Text) - 1, pager.PageSize, true);}

Sorting Data

You can sort the data that is displayed in a ListView control by adding a button to the LayoutTemplate template and setting the button's CommandName property to "Sort". You set the CommandArgument property of the button to the column name that you want to sort by. Clicking the Sort button repeatedly toggles the sort direction between Ascendingand Descending.

You can specify multiple column names in the CommandArgument property of the Sort button. However, the ListView control applies the sort direction to the complete list of columns. As a result, only the last column of the list has the sort direction applied. For example, if the CommandArgument contains "LastName, FirstName", clicking the Sort button repeatedly produces a sort expression like "LastName, FirstName ASC" or "LastName, FirstName DESC".

The following example shows a ListView control that includes a Sort button to sort the data by last name.

Copy<asp:ListView runat="server" ID="ListView1" DataSourceID="SqlDataSource1"> <LayoutTemplate> <asp:LinkButton runat="server" ID="SortButton"

Page 61: Best Tutorial of c#

Text="Sort" CommandName="Sort" CommandArgument="LastName" /> <table runat="server" id="table1"> <tr runat="server" id="itemPlaceholder"> </tr> </table> <asp:DataPager runat="server" ID="DataPager" PageSize="20"> <Fields> <asp:NumericPagerField ButtonCount="10" PreviousPageText="<--" NextPageText="-->" /> </Fields> </asp:DataPager> </LayoutTemplate> <ItemTemplate> <tr runat="server"> <td><asp:Label runat="server" ID="FirstNameLabel" Text='<%# Eval("FirstName")' /></td> <td><asp:Label runat="server" ID="LastNameLabel" Text='<%# Eval("LastName")' /></td> </tr> </ItemTemplate></asp:ListView>

Setting the Sort Expression Dynamically

You can create customized sorting by setting the sort expression of a ListView control dynamically. To do so, you call the Sort method or handle the Sorting event.

The following example shows a handler for the Sorting event. The code applies the same sort direction to all the columns in the SortExpression property.

C#

protected void EmployeesListView_OnSorting(object sender, ListViewSortEventArgs e){ if (String.IsNullOrEmpty(e.SortExpression)) { return; } string direction = ""; if (ViewState["SortDirection"] != null) direction = ViewState["SortDirection"].ToString();

if (direction == "ASC") direction = "DESC"; else direction = "ASC";

ViewState["SortDirection"] = direction;

string[] sortColumns = e.SortExpression.Split(','); string sortExpression = sortColumns[0] + " " + direction; for (int i = 1; i < sortColumns.Length; i++) sortExpression += ", " + sortColumns[i] + " " + direction; e.SortExpression = sortExpression;

Page 62: Best Tutorial of c#

}

Modifying Data

You can create templates for the ListView control that enable users to edit, insert, or delete a single data item.

To enable users to edit a data item, you can add a EditItemTemplate template to the ListView control. When an item is switched to edit mode, the ListView control displays the item by using the edit template. The template should include data-bound controls where the user can edit values. For example, the template can include text boxes where users can edit existing values.

To enable users to insert a new item, you can add a InsertItemTemplate template to the ListView control. As with the edit template, the insert template should include data-bound controls that enable data entry. The InsertItemTemplate template is rendered either at the start or at the end of the displayed items. You specify where the InsertItemTemplatetemplate is rendered by using the InsertItemPosition property of the ListView control.

You typically add buttons to templates to enable users to specify what action they want to take. For example, you can add a Delete button to an item template to enable users to delete that item.

You can add an Edit button to an item template to enable the user to switch to edit mode. In the EditItemTemplate you can include an Update button that enables users to save changes. You can also include a Cancel button that enables users to switch back to display mode without saving changes.

You define the action that a button will take by setting the CommandName property of the button. The following table lists values for the CommandName property that theListView control has built-in behavior for.

Select

Displays the content of the SelectedItemTemplate template for the selected item.

Insert

In an InsertItemTemplate template, specifies that the contents of data-bound controls should be saved in the data source.

Edit

Specifies that the ListView control should switch to edit mode and display the item by using the EditItemTemplate template.

Update

In an EditItemTemplate template, specifies that the contents of data-bound controls should be saved in the data source.

Page 63: Best Tutorial of c#

Delete

Deletes the item from the data source.

Cancel

Cancels the current action. When the EditItemTemplate template is displayed, canceling the action displays the SelectedItemTemplate template if the item is the current selected item; otherwise the ItemTemplate template is displayed. When the InsertItemTemplate template is displayed, canceling the action displays an emptyInsertItemTemplate template.

(Custom value)

By default, takes no action. You can supply a custom value for the CommandName property. In the ItemCommand event, you can then test for the value and take action.

For an example of a ListView control that is configured to enable editing, deleting, and inserting, see Walkthrough: Modifying Data Using the ListView Web Server Control.

Applying Styles to ListView Items

The ListView control does not support style properties such as BackColor and Font. In order to apply styles to the ListView control, you must use cascading style sheets (CSS) classes or inline style elements for individual controls inside the ListView templates.

Some objects support properties that enable you to style elements of the output. For example, the NumericPagerField object includes the following properties:

A NumericButtonCssClass property that enables you to specify the CSS class name for the buttons that move to pages of data by number.

A CurrentPageLabelCssClass property that enables you to specify the CSS class name for the current page number.

A NextPreviousButtonCssClass property that enables you to specify the CSS class name for the buttons that move to the next or previous group of numeric buttons.

Class Reference

The following table lists the key classes that are related to the ListView control.

Class Description

ListView A server control that displays the values of a data source by using user-defined templates. You can configure the control to enable users to select, sort, delete, edit, and insert records.

ListViewItem An object that represents an item in the ListView control.

ListViewDataItem An object that represents a data item in the ListView control.

ListViewItemType An enumeration that identifies the function of items in a ListView control.

Page 64: Best Tutorial of c#

DataPager A server control that provides paging functionality for controls that implement the IPageableItemContainerthe ListView control.

NumericPagerField A DataPager field that enables users to select a page of data by page number.

NextPreviousPagerField

A DataPager field that enables users to move through pages of data one page at a time, or to jump to the first or last page of data.

TemplatePagerField A DataPager field that enables users to create a custom paging UI.

To add basic validation

1. Switch to Design view.2. From the Validation group of the Toolbox, drag a RequiredFieldValidator control and

drop it next to the textEmail text box.3. Set the following properties of the RequiredFieldValidator control:

Property Setting

ControlToValidate

textEmail

Binds the validator control to the text box whose contents you want to validate.

Display Dynamic

Specifies that the control renders (and takes up space in the page) only if required in order to display an error.

ErrorMessage E-mail address is required.

Displays text in a summary error by using a ValidationSummary control, which you will configure later in the walkthrough.

Text *

A star is a conventional way of indicating that a field is required. This text is displayed in the validation control and is displayed only if there is an error.

ValidationGroup AllValidators

As with radio buttons, you can group validators into groups that are treated as a unit. You will learn more about grouping validators later in the walkthrough.

Page 65: Best Tutorial of c#

4. What you have done is added a test to be sure the user enters an e-mail address. The validator control performs all the checking and error display without requiring you to add code to the page.

5. From the Validation group of the Toolbox, drag a RegularExpressionValidator control and drop it next to the RequiredFieldValidator you just added.

6. Set the following properties of the RegularExpressionValidator control:

1. Property 2. Setting

ControlToValidate textEmail

You are again validating the user's entry in the e-mail box.

Display Dynamic

ErrorMessage E-mail addresses must be in the format of [email protected].

This is a longer error message that is displayed by using a ValidationSummary control.

Text Invalid format!

This is a short error message that is displayed in the validation control.

ValidationGroup AllValidators

As with radio buttons, you can group validators into groups that are treated as a unit. You will learn more about grouping validators later in the walkthrough.

7. With the RegularExpressionValidator control still selected, in the Property window click the ellipsis button in the ValidationExpression box.

Regular expressions constitute a language that can be used to find precisely defined patterns in strings. In the RegularExpressionValidator control, you define a regular expression for the pattern that is valid — in this case, the pattern for a valid e-mail address.

The Regular Expression Editor contains a list of commonly used regular expressions so that you can use the validator control without learning regular expression syntax.

8. In the Standard Expressions list, click Internet E-mail Address.

The regular expression for an e-mail address is put in the Validation Expression box.

9. Click OK to close the dialog box.10. Add another RequiredFieldValidator control, using the instructions earlier in this

procedure. However, this time bind it to the textNumberInParty text box and set itsErrorMessage property to Please indicate how many people are in your party.

11. From the Validation group of the Toolbox, drag a RangeValidator control and drop it next to the RequiredFieldValidator you just added.

12. Set the following properties of the RangeValidator control:

1. Property 2. Setting

Page 66: Best Tutorial of c#

ControlToValidate textNumberInParty

Display Dynamic

ErrorMessage Enter a number between 1 and 20 for the number of people in your party.

MaximumValue 20

In this case, an arbitrary but high value.

MinimumValue 1

In this application, a reservation requires at least one person.

Text Enter a number between 1 and 20.

Type Integer

ValidationGroup AllValidators

13. The RangeValidator control performs two functions: it ensures that the data a user enters is numeric, and it checks that the number is between the specified minimum and maximum values.

Testing the Page

You can now test the validator controls that you have so far.

To test basic validation

1. Press CTRL+F5 to run the page.2. When the page appears in the browser, click the Submit Request button.

Several validation errors are displayed, because you have not filled in some required fields. Note that the validation errors are displayed immediately — the page is not submitted. By default, the validator controls inject client-side ECMAScript (JavaScript) into the page to perform validation checking in the browser. This gives users instant feedback on validation errors; without the client script, checking for validation errors would require a round trip to the server, which could be slow at times. In fact, you cannot submit the page until the client-side validation checks all pass. (The same validation check is performed again when the page is submitted as a security precaution.)

3. Check the validation on the textEmail text box by typing an invalid e-mail address, and then again with a valid e-mail address such as your own.

4. Check that you can enter only numeric values between 1 and 20 in the Number of people in party text box.

5. When you have entered valid values, click the Submit Request button. If the validation passes for all controls, you will see the message Your reservation has been processed.

Page 67: Best Tutorial of c#

6. After you have confirmed that validation is working as expected, close the browser.

If validation is not working as expected, double-check that you have made all the property settings listed above and then run the page again.

Alternative Ways to Display Error Information

By default, validator controls display error text in-place; that is, they display the value of the control's Text property at the control's location in the page. At times you might want to display error information in different ways. The ASP.NET validator controls provide you with these additional options:

Summarize all validation errors in one place. You can do this in addition to or instead of showing in-place errors. Displaying error summaries also allows you to display longer error messages.

Display a pop-up message in the browser with error information. This option works only on script-enabled browsers.

You can add both of these display options using the ValidationSummary control. In this part of the walkthrough, you'll add both display features to the page.

To display validation information in alternative ways

1. From the Validation group of the Toolbox, drag a ValidationSummary control onto the page.

2. Set the ValidationSummary control's ValidationGroup property to AllValidators.3. Run the page.4. Perform the same testing you did earlier in the walkthrough.

For each error, you see error information in two places. A short error message (the validator's Text property value) is displayed where the validator control is. The longer error message (the control's ErrorMessage property value) is displayed in the ValidationSummary control.

5. Close the browser.6. Set the ValidationSummary control's ShowMessageBox property to true.7. Run the page.8. Perform the same tests.

This time, each error results in a pop-up message in the browser.

9. Close the browser.

Adding Custom Validation to Check Date Entry

Page 68: Best Tutorial of c#

The ASP.NET validation controls do not include a control that automatically checks for a valid date. However, you can use the CustomValidator control for that purpose. The custom validator allows you to write your own validation code to check for any condition your application requires. In this walkthrough, you will use the CustomValidator to check that the value the user enters into the textPreferredDate text box can be converted to a date value.

You will add two blocks of custom validation code. The first is the custom validation code that runs when the page is submitted. You must always have server-side validation logic for a CustomValidator control. You will also write some client script (ECMAScript or JavaScript) that performs a similar check in the browser, so that the user can have immediate feedback.

To use a CustomValidator control to check for a valid date

1. From the Validation group of the Toolbox, drag a CustomValidator control onto the page and position it next to the textPreferredDate text box.

2. Set the following properties of the CustomValidator control:

Property Setting

ControlToValidate textPreferredDate

Display Dynamic

ErrorMessage Enter a date in the format m/d/yyyy.

Text Invalid date format (requires m/d/yyyy).

ValidationGroup AllValidators

3. Double-click the CustomValidator control to create a handler for its ServerValidate event and then add the following highlighted code:

VB

C#

C++

F#

JScript

Copy

This language is not supported, or no code example is available.

VB

C#

C++

Page 69: Best Tutorial of c#

F#

JScript

Copy

protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args){ try { DateTime.ParseExact(args.Value, "d", System.Globalization.DateTimeFormatInfo.InvariantInfo); args.IsValid = true; } catch { args.IsValid = false; }}

This code runs when the user submits the page. The code interacts with the validator control using the ServerValidateEventArgs (args) object passed into the handler. The value that the user has entered into the textPreferredDate text box is passed as the args object's Value property. After you have checked whether the user's entry is valid, you set the args object's IsValid property to true or false. If you set it to false, the validator will display its error message.

In this example, the code uses a try-catch block to determine whether the user's entry can be converted into a DateTime object. If the user enters an invalid value (anything that does not conform to a date in the format m/d/yyyy), the DateTime object's ParseExact method throws an exception, and the Catch block is executed.

Note

The value of the provider parameter of the DateTime.ParseExact method is culture independent. If you need to use the current culture, you can set provider to null.

4. In the Button_Click handler, add the following highlighted code:

VB

C#

C++

F#

Page 70: Best Tutorial of c#

JScript

Copy

This language is not supported, or no code example is available.

VB

C#

C++

F#

JScript

Copy

protected void buttonSubmit_Click(object sender, EventArgs e){ if(Page.IsValid) { labelMessage.Text = "Your reservation has been processed."; } else { labelMessage.Text = "Page is not valid."; }}

When you use a CustomValidator control, you must check the Page.IsValidproperty in any server-side processing to be sure that all the validation checks have passed. TheIsValid property returns the cumulative state of all the validator controls on the page. This property is used to make sure that all validation checks have passed any server-side processing.

You have now added the server-side code for the CustomValidator control to check for a valid date. As you know from earlier in the walkthrough, validator controls also check a user's entry using client script. You can add client script to the CustomValidator control as well. In effect, you write client script that duplicates the logic that your server-side validation performs. Writing client-side custom validation code is not always practical (for example, if the custom code validates a user's entry by looking in a server-side database). However, in this case you can create client-side code that performs essentially the same check that your server-side code is performing.

To add client script to the CustomValidator control

1. Open or switch to ValidationExample.aspx.2. In the <head> element of the page, add the following client script block:

Page 71: Best Tutorial of c#

Copy

<script language="javascript">function validateDate(oSrc, args){ var iDay, iMonth, iYear; var arrValues; arrValues = args.Value.split("/"); iMonth = arrValues[0]; iDay = arrValues[1]; iYear = arrValues[2];

var testDate = new Date(iYear, iMonth - 1, iDay); if ((testDate.getDate() != iDay) || (testDate.getMonth() != iMonth - 1) || (testDate.getFullYear() != iYear)) { args.IsValid = false; return; } return true;}</script>

Note

ECMAScript (JavaScript) is case-sensitive; enter the code exactly as you see it here.

This code is similar to the server-side validation check, but not as strict. The user's entry is passed into the function as the args object's Value property, and you can set the object's IsValid property to indicate whether the value passes validation. In this example, the code checks to make sure valid numeric dates were entered.

Note that the code for the custom validation is slightly different in client script than it is in server code. ECMAScript does not provide exactly the same functionality as that in the .NET Framework. Therefore, the ECMAScript parses the entered text instead of the ParseExact code that you use on the server to check the date. However, the two validation checks (client and server) are similar enough to provide the functionality you need.

3. Put the insertion point in the <asp:customvalidator> element to select it.4. In the Properties window, set the control's ClientValidationFunction property

to validateDate, which is the name of the ECMAScript function that you just created.

You have now added a custom validation check that works both in client script to check the user's entry immediately and then again when the page is submitted to the server.

Testing Custom Validation

You can now test that your custom validation is working properly.

Page 72: Best Tutorial of c#

To test custom validation

1. Temporarily disable the client-side validation by setting the EnableClientScript property of the CustomValidator control to false.

2. Press CTRL+F5 to run the page.3. Fill in an e-mail address and the number of people in the party so that the validation

for those fields passes.4. In the date text box, enter a string that is obviously not a date and then click

the Submit Request button.

Your page performs a round trip to the Web server, where the server-side validation fails. The test for IsValid fails and labelMessage says "Page is not valid."

5. Fill in a valid date value (such as 11/17/2005) and click the button.

This time, the date value passes validation, so you see the confirmation message created in the button's Click handler.

6. Close the browser.7. Re-enable client-side validation by setting the EnableClientScript property of

the CustomValidator control back to true.8. Run the page again and enter valid values for the e-mail address and number of

people in the party.

Enter an invalid date value into the date text box and then press the TAB key. (Do not click the button.)

As soon as the date text box loses focus, the client-side validation script runs and you see an error message.

Note

If you are using the auto-complete option in Internet Explorer, selecting a value from the auto-complete list will fill a value into the text box, but the client-side validator will not run.

9. Click the Submit Request button.

Because the client-side validation for the date text box has failed, the page is not submitted.

10. Correct the date value and press the TAB key again.

The error message disappears. You can now submit the form.

Adding Optional Controls with Conditional Validation

Page 73: Best Tutorial of c#

In the final part of the walkthrough, you will add some optional information to the reservation form. Users can check a box to indicate that they want telephone confirmation of their reservation. If they do, they must enter their telephone number. The page will therefore contain two additional controls: a check box and a text box.

As before, you will use validation to check the user's entries. You will use a RequiredFieldValidator control to be sure that users enter a phone number, and aRegularExpressionValidator control to check its format. The telephone number is optional; you need to check the phone number only if the user has selected the Confirm reservation by phone check box. You therefore will write some simple code that turns validation on or off for the telephone number depending on the state of the check box.

To add conditional validation

1. From the Standard group of the Toolbox, drag a CheckBox control onto the page and set the following properties:

Property Setting

ID checkPhoneConfirmation

AutoPostBack True

When the user clicks the check box, the page will perform a round trip and conditionally enable the text box and the validation for it.

CausesValidation False

Clicking the CheckBox will not automatically cause validation.

Text Confirm reservation by telephone.

2. Drag a TextBox control onto the page underneath the CheckBox control and set the following properties:

1. Property 2. Settings

ID textPhoneNumber

Enabled False

The text box will not be enabled until the user clicks the check box.

3. Type text such as Telephone number: next to the phone number text box as a caption.

4. From the Validation group of the Toolbox, drag a RequiredFieldValidator onto the page and set the following properties:

Property Setting

ID validatorRequiredPhoneNumber

Page 74: Best Tutorial of c#

You did not set the ID of validator controls earlier in the walkthrough, but in this case you will be referring to the validator control in code, so you it is helpful to give it a mnemonic ID.

ControlToValidate

textPhoneNumber

Display Dynamic

ErrorMessage You must provide a phone number.

Text *

ValidationGroup (Leave blank)

If this property is blank, the validator does not belong to the AllValidators group that you established for the other validator controls on the page. As a consequence, by default this validator is not checked when the buttonSubmit

5. Drag a RegularExpressionValidator control onto the page and set the following properties:

Property Setting

ID validatorRegExPhoneNumber

ControlToValidate textPhoneNumber

Display Dynamic

ErrorMessage Phone number format is invalid

Text Invalid format

ValidationExpression (Use the Regular Expression Editor dialog box to select U.S. Phone Number or another phone number expression.)

ValidationGroup (Leave blank)

6. Double-click the checkPhoneConfirmation control to create a handler for its CheckedChanged event and then add the following highlighted code:

VB

C#

C++

F#

JScript

Copy

Page 75: Best Tutorial of c#

This language is not supported, or no code example is available.

VB

C#

C++

F#

JScript

Copy

protected void checkPhoneConfirmation_CheckedChanged( object sender, EventArgs e){ if(checkPhoneConfirmation.Checked) { textPhoneNumber.Enabled = true; validatorRequiredPhoneNumber.ValidationGroup = "AllValidators"; validatorRegExPhoneNumber.ValidationGroup = "AllValidators"; } else { textPhoneNumber.Enabled = false; validatorRequiredPhoneNumber.ValidationGroup = ""; validatorRegExPhoneNumber.ValidationGroup = ""; }}

When the user clicks the check box, the two validators associated with the text box are added to the validation group that the other validator controls belong to. The effect is that all the validators on the page, including those for the phone number, will be checked when the user submits the page. If the user clears the check box, the validators are removed from the group and are therefore not processed when the Submit Request button is clicked.

Testing Conditional Validation

You can now test that conditional validation is working properly.

To test conditional validation

1. Press CTRL+F5 to run the page.2. Enter information for the e-mail address, the number of people in the party, and the

date.3. Click Submit Request.

Page 76: Best Tutorial of c#

The page is submitted and you see the confirmation message.

4. Select the Confirm reservation by phone check box.5. Click Submit Request again.

This time, you see an error message (a star next to the phone text box). When you clicked the check box, you enabled validation for the text box.

6. Enter an invalid phone number and then click Submit Request again to confirm that the text box will not accept an invalid phone number.

7. Enter a correctly formatted phone number and click the submit button to confirm that the validator control accepts well-formed data.

Note

If you have selected U.S. Phone Number in the Regular Expression Editor for the ValidationExpression property of the RegularExpressionValidator control, a correctly formatted phone number consists of the area code (optional field with 3 numeric characters, enclosed in parentheses or followed by a dash), followed by a set of 3 numeric characters, a dash and then a set of 4 numeric characters. Valid examples are (425) 555-0123, 425-555-0123 or 555-0123.

RequiredFieldValidator Properties

Page 77: Best Tutorial of c#

The RequiredFieldValidator type exposes the following members.

Properties  Name Description

AccessKey Gets or sets the access key that allows you to quickly navigate to the Web server control. (Inherited from WebControl.)

Adapter Gets the browser-specific adapter for the control. (Inherited from Control.)

AppRelativeTemplateSourceDirectory Gets or sets the application-relative virtual directory of the Page or UserControl object that contains this control. (Inherited from Control

AssociatedControlID This property is not supported. (Inherited from BaseValidator.)

Attributes Gets the collection of arbitrary attributes (for rendering only) that do not correspond to properties on the control.(Inherited from WebControl.)

BackColor Gets or sets the background color of the Web server control. (Inherited from WebControl.)

BindingContainer Infrastructure. Gets the control that contains this control's data binding. (Inherited from Control.)

BorderColor Gets or sets the border color of the Web control. (Inherited from WebControl.)

BorderStyle Gets or sets the border style of the Web server control. (Inherited from WebControl.)

BorderWidth Gets or sets the border width of the Web server control. (Inherited from WebControl.)

ChildControlsCreated Gets a value that indicates whether the server control's child controls have been created. (Inherited from Control.)

ClientID Gets the control ID for HTML markup that is generated by ASP.NET. (Inherited from Control.)

ClientIDMode Gets or sets the algorithm that is used to generate the value of the ClientID property. (Inherited from Control.)

ClientIDSeparator Gets a character value representing the separator character used in the ClientID property. (Inherited from Control.)

Context Gets the HttpContext object associated with the server control for the current Web request. (Inherited from Control.)

Controls Gets a ControlCollection object that represents the child controls for a specified server control in the UI hierarchy.

Page 78: Best Tutorial of c#

(Inherited from Control.)

ControlStyle Gets the style of the Web server control. This property is used primarily by control developers. (Inherited fromWebControl.)

ControlStyleCreated Gets a value indicating whether a Style object has been created for the ControlStyle property. This property is primarily used by control developers. (Inherited from WebControl.)

ControlToValidate Gets or sets the input control to validate. (Inherited from BaseValidator.)

CssClass Gets or sets the Cascading Style Sheet (CSS) class rendered by the Web server control on the client. (Inherited fromWebControl.)

DataItemContainer Gets a reference to the naming container if the naming container implements IDataItemContainer. (Inherited from Control.)

DataKeysContainer Gets a reference to the naming container if the naming container implements IDataKeysControl. (Inherited from Control.)

DesignMode Gets a value indicating whether a control is being used on a design surface. (Inherited from Control.)

Display Gets or sets the display behavior of the error message in a validation control. (Inherited from BaseValidator.)

EnableClientScript Gets or sets a value indicating whether client-side validation is enabled. (Inherited from BaseValidator.)

Enabled Gets or sets a value that indicates whether the validation control isenabled. (Inherited from BaseValidator.)

EnableTheming Gets or sets a value indicating whether themes apply to this control. (Inherited from WebControl.)

EnableViewState Gets or sets a value indicating whether the server control persists its view state, and the view state of any child controls it contains, to the requesting client. (Inherited from Control.)

ErrorMessage Gets or sets the text for the error message displayed in a ValidationSummary control when validation fails. (Inherited fromBaseValidator.)

Events Gets a list of event handler delegates for the control. This property is read-only. (Inherited from Control.)

Font Gets the font properties associated with the Web server control. (Inherited from WebControl.)

ForeColor Gets or sets the color of the message displayed when validation fails. (Inherited from BaseValidator.)

Page 79: Best Tutorial of c#

HasAttributes Gets a value indicating whether the control has attributes set. (Inherited from WebControl.)

HasChildViewState Gets a value indicating whether the current server control's child controls have any saved view-state settings. (Inherited fromControl.)

Height Gets or sets the height of the Web server control. (Inherited from WebControl.)

ID Gets or sets the programmatic identifier assigned to the server control. (Inherited from Control.)

IdSeparator Infrastructure. Gets the character used to separate control identifiers. (Inherited from Control.)

InitialValue Gets or sets the initial value of the associated input control.

IsChildControlStateCleared Gets a value indicating whether controls contained within this control have control state. (Inherited from Control.)

IsEnabled Gets a value indicating whether the control is enabled. (Inherited from WebControl.)

IsTrackingViewState Gets a value that indicates whether the server control is saving changes to its view state. (Inherited from Control.)

IsValid Gets or sets a value that indicates whether the associated input control passes validation. (Inherited from BaseValidator.)

IsViewStateEnabled Gets a value indicating whether view state is enabled for this control. (Inherited from Control.)

LoadViewStateByID Gets a value indicating whether the control participates in loading its view state by ID instead of index. (Inherited fromControl.)

NamingContainer Gets a reference to the server control's naming container, which creates a unique namespace for differentiating between server controls with the same Control.ID property value. (Inherited from

Page Gets a reference to the Page instance that contains the server control.

Parent Gets a reference to the server control's parent control in the page control hierarchy.

PropertiesValid Gets a value that indicates whether the control specified by the ControlToValidatefromBaseValidator.)

RenderingCompatibility Gets a value that specifies the ASP.NET version that rendered HTML will be compatible with.

RenderUplevel Gets a value that indicates whether the client's browser supports "uplevel" rendering.

SetFocusOnError Gets or sets a value that indicates whether focus is set to the control specified by the

Page 80: Best Tutorial of c#

validation fails. (Inherited from BaseValidator.)

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

SkinID Gets or sets the skin to apply to the control. (Inherited from WebControl

Style Gets a collection of text attributes that will be rendered as a style attribute on the outer tag of the Web server control.(Inherited from WebControl.)

SupportsDisabledAttribute Gets a value that indicates whether the control should set the disabled"disabled" when the control's IsEnabled property is false. (Inherited from

TabIndex Gets or sets the tab index of the Web server control. (Inherited from

TagKey Gets the HTML tag that is used to render the Label control. (Inherited from

TagName Gets the name of the control tag. This property is used primarily by control developers.

TemplateControl Gets or sets a reference to the template that contains this control. (Inherited from

TemplateSourceDirectory Gets the virtual directory of the Page or UserControl that contains the current server control.

Text Gets or sets the text displayed in the validation control when validation fails.

ToolTip Gets or sets the text displayed when the mouse pointer hovers over the Web server control.from WebControl.)

UniqueID Gets the unique, hierarchically qualified identifier for the server control.

ValidationGroup Gets or sets the name of the validation group to which this validation control belongs.

ViewState Gets a dictionary of state information that allows you to save and restore the view state of a server control across multiple requests for the same page. (Inherited from Control.)

ViewStateIgnoresCase Gets a value that indicates whether the StateBag object is case-insensitive.

ViewStateMode Gets or sets the view-state mode of this control. (Inherited from Control

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

Width Gets or sets the width of the Web server control. (Inherited from WebControl

Page 81: Best Tutorial of c#

RegularExpressionValidator Properties

The RegularExpressionValidator type exposes the following members.

Properties

  Name Description

AccessKey Gets or sets the access key that allows you to quickly navigate to the Web server control. (Inherited from WebControl.)

Adapter Gets the browser-specific adapter for the control. (Inherited from Control.)

AppRelativeTemplateSourceDirectory Gets or sets the application-relative virtual directory of the Page or UserControl object that contains this control. (Inherited from Control

AssociatedControlID This property is not supported. (Inherited from BaseValidator.)

Attributes Gets the collection of arbitrary attributes (for rendering only) that do not correspond to properties on the control.(Inherited from WebControl.)

BackColor Gets or sets the background color of the Web server control. (Inherited from

BindingContainer Infrastructure. Gets the control that contains this control's data binding.

BorderColor Gets or sets the border color of the Web control. (Inherited from WebControl

BorderStyle Gets or sets the border style of the Web server control. (Inherited from

BorderWidth Gets or sets the border width of the Web server control. (Inherited from

ChildControlsCreated Gets a value that indicates whether the server control's child controls have been created.

ClientID Gets the control ID for HTML markup that is generated by ASP.NET. (Inherited from

ClientIDMode Gets or sets the algorithm that is used to generate the value of the ClientID

ClientIDSeparator Gets a character value representing the separator character used in the

Context Gets the HttpContext object associated with the server control for the current Web request.

Controls Gets a ControlCollection object that represents the child controls for a specified server control in the UI hierarchy. (Inherited from Control.)

ControlStyle Gets the style of the Web server control. This property is used primarily by control developers.fromWebControl.)

ControlStyleCreated Gets a value indicating whether a Style object has been created for the

Page 82: Best Tutorial of c#

used by control developers. (Inherited from WebControl.)

ControlToValidate Gets or sets the input control to validate. (Inherited from BaseValidator

CssClass Gets or sets the Cascading Style Sheet (CSS) class rendered by the Web server control on the client.fromWebControl.)

DataItemContainer Gets a reference to the naming container if the naming container implementsfrom Control.)

DataKeysContainer Gets a reference to the naming container if the naming container implementsfrom Control.)

DesignMode Gets a value indicating whether a control is being used on a design surface.

Display Gets or sets the display behavior of the error message in a validation control.

EnableClientScript Gets or sets a value indicating whether client-side validation is enabled.

Enabled Gets or sets a value that indicates whether the validation control is enabled.

EnableTheming Gets or sets a value indicating whether themes apply to this control.

EnableViewState Gets or sets a value indicating whether the server control persists its view state, and the view state of any child controls it contains, to the requesting client. (Inherited from Control.)

ErrorMessage Gets or sets the text for the error message displayed in a ValidationSummaryfromBaseValidator.)

Events Gets a list of event handler delegates for the control. This property is read-only.

Font Gets the font properties associated with the Web server control. (Inherited from

ForeColor Gets or sets the color of the message displayed when validation fails.

HasAttributes Gets a value indicating whether the control has attributes set. (Inherited from

HasChildViewState Gets a value indicating whether the current server control's child controls have any saved view-state settings.fromControl.)

Height Gets or sets the height of the Web server control. (Inherited from WebControl

ID Gets or sets the programmatic identifier assigned to the server control.

IdSeparator Infrastructure. Gets the character used to separate control identifiers.

IsChildControlStateCleared Gets a value indicating whether controls contained within this control have control state.

IsEnabled Gets a value indicating whether the control is enabled. (Inherited from

IsTrackingViewState Gets a value that indicates whether the server control is saving changes to its view state.

IsValid Gets or sets a value that indicates whether the associated input control passes validation.from BaseValidator.)

IsViewStateEnabled Gets a value indicating whether view state is enabled for this control.

Page 83: Best Tutorial of c#

LoadViewStateByID Gets a value indicating whether the control participates in loading its view state byfromControl.)

NamingContainer Gets a reference to the server control's naming container, which creates a unique namespace for differentiating between server controls with the same Control.ID property value. (Inherited from

Page Gets a reference to the Page instance that contains the server control. (Inherited from Control.)

Parent Gets a reference to the server control's parent control in the page control hierarchy.

PropertiesValid Gets a value that indicates whether the control specified by the ControlToValidatefromBaseValidator.)

RenderingCompatibility Gets a value that specifies the ASP.NET version that rendered HTML will be compatible with. (Inherited from Control.)

RenderUplevel Gets a value that indicates whether the client's browser supports "uplevel" rendering.

SetFocusOnError Gets or sets a value that indicates whether focus is set to the control specified by thevalidation fails. (Inherited from BaseValidator.)

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

SkinID Gets or sets the skin to apply to the control. (Inherited from WebControl

Style Gets a collection of text attributes that will be rendered as a style attribute on the outer tag of the Web server control.(Inherited from WebControl.)

SupportsDisabledAttribute Gets a value that indicates whether the control should set the disabled"disabled" when the control's IsEnabled property is false. (Inherited from

TabIndex Gets or sets the tab index of the Web server control. (Inherited from

TagKey Gets the HTML tag that is used to render the Label control. (Inherited from

TagName Gets the name of the control tag. This property is used primarily by control developers.

TemplateControl Gets or sets a reference to the template that contains this control. (Inherited from

TemplateSourceDirectory Gets the virtual directory of the Page or UserControl that contains the current server control.

Text Gets or sets the text displayed in the validation control when validation fails.

ToolTip Gets or sets the text displayed when the mouse pointer hovers over the Web server control.from WebControl.)

UniqueID Gets the unique, hierarchically qualified identifier for the server control.

ValidationExpression Gets or sets the regular expression that determines the pattern used to validate a field.

ValidationGroup Gets or sets the name of the validation group to which this validation control belongs.

ViewState Gets a dictionary of state information that allows you to save and restore the view state of a server control across

Page 84: Best Tutorial of c#

multiple requests for the same page. (Inherited from Control.)

ViewStateIgnoresCase Gets a value that indicates whether the StateBag object is case-insensitive.

ViewStateMode Gets or sets the view-state mode of this control. (Inherited from Control

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

Width Gets or sets the width of the Web server control. (Inherited from WebControl

RangeValidator Properties

The RangeValidator type exposes the following members.

Properties

  Name Description

AccessKey Gets or sets the access key that allows you to quickly navigate to the Web server control.

Adapter Gets the browser-specific adapter for the control. (Inherited from Control

AppRelativeTemplateSourceDirectory Gets or sets the application-relative virtual directory of the Page or UserControlcontrol. (Inherited from Control.)

AssociatedControlID This property is not supported. (Inherited from BaseValidator.)

Attributes Gets the collection of arbitrary attributes (for rendering only) that do not correspond to properties on the control.(Inherited from WebControl.)

BackColor Gets or sets the background color of the Web server control. (Inherited from

BindingContainer Infrastructure. Gets the control that contains this control's data binding.

BorderColor Gets or sets the border color of the Web control. (Inherited from WebControl

BorderStyle Gets or sets the border style of the Web server control. (Inherited from

BorderWidth Gets or sets the border width of the Web server control. (Inherited from

ChildControlsCreated Gets a value that indicates whether the server control's child controls have been created.

ClientID Gets the control ID for HTML markup that is generated by ASP.NET. (Inherited from

ClientIDMode Gets or sets the algorithm that is used to generate the value of the ClientID

Page 85: Best Tutorial of c#

ClientIDSeparator Gets a character value representing the separator character used in the

Context Gets the HttpContext object associated with the server control for the current Web request.

Controls Gets a ControlCollection object that represents the child controls for a specified server control in the UI hierarchy. (Inherited from Control.)

ControlStyle Gets the style of the Web server control. This property is used primarily by control developers.fromWebControl.)

ControlStyleCreated Gets a value indicating whether a Style object has been created for theused by control developers. (Inherited from WebControl.)

ControlToValidate Gets or sets the input control to validate. (Inherited from BaseValidator

CssClass Gets or sets the Cascading Style Sheet (CSS) class rendered by the Web server control on the client.fromWebControl.)

CultureInvariantValues Gets or sets a value indicating whether values are converted to a culture-neutral format before being compared. (Inherited from BaseCompareValidator.)

DataItemContainer Gets a reference to the naming container if the naming container implementsfrom Control.)

DataKeysContainer Gets a reference to the naming container if the naming container implementsfrom Control.)

DesignMode Gets a value indicating whether a control is being used on a design surface.

Display Gets or sets the display behavior of the error message in a validation control.

EnableClientScript Gets or sets a value indicating whether client-side validation is enabled.

Enabled Gets or sets a value that indicates whether the validation control is enabled.

EnableTheming Gets or sets a value indicating whether themes apply to this control.

EnableViewState Gets or sets a value indicating whether the server control persists its view state, and the view state of any child controls it contains, to the requesting client. (Inherited from Control.)

ErrorMessage Gets or sets the text for the error message displayed in a ValidationSummaryfromBaseValidator.)

Events Gets a list of event handler delegates for the control. This property is read-only.

Font Gets the font properties associated with the Web server control. (Inherited from

ForeColor Gets or sets the color of the message displayed when validation fails.

HasAttributes Gets a value indicating whether the control has attributes set. (Inherited from

HasChildViewState Gets a value indicating whether the current server control's child controls have any saved view-state settings.fromControl.)

Height Gets or sets the height of the Web server control. (Inherited from WebControl

Page 86: Best Tutorial of c#

ID Gets or sets the programmatic identifier assigned to the server control.

IdSeparator Infrastructure. Gets the character used to separate control identifiers.

IsChildControlStateCleared Gets a value indicating whether controls contained within this control have control state.

IsEnabled Gets a value indicating whether the control is enabled. (Inherited from

IsTrackingViewState Gets a value that indicates whether the server control is saving changes to its view state.

IsValid Gets or sets a value that indicates whether the associated input control passes validation.from BaseValidator.)

IsViewStateEnabled Gets a value indicating whether view state is enabled for this control.

LoadViewStateByID Gets a value indicating whether the control participates in loading its view state byfromControl.)

MaximumValue Gets or sets the maximum value of the validation range.

MinimumValue Gets or sets the minimum value of the validation range.

NamingContainer Gets a reference to the server control's naming container, which creates a unique namespace for differentiating between server controls with the same Control.ID property value. (Inherited from

Page Gets a reference to the Page instance that contains the server control.

Parent Gets a reference to the server control's parent control in the page control hierarchy.

PropertiesValid Gets a value that indicates whether the control specified by the ControlToValidatefromBaseValidator.)

RenderingCompatibility Gets a value that specifies the ASP.NET version that rendered HTML will be compatible with.

RenderUplevel Gets a value that indicates whether the client's browser supports "uplevel" rendering.

SetFocusOnError Gets or sets a value that indicates whether focus is set to the control specified by thevalidation fails. (Inherited from BaseValidator.)

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

SkinID Gets or sets the skin to apply to the control. (Inherited from WebControl

Style Gets a collection of text attributes that will be rendered as a style attribute on the outer tag of the Web server control.(Inherited from WebControl.)

SupportsDisabledAttribute Gets a value that indicates whether the control should set the disabled"disabled" when the control's IsEnabled property is false. (Inherited from

TabIndex Gets or sets the tab index of the Web server control. (Inherited from

TagKey Gets the HTML tag that is used to render the Label control. (Inherited from

TagName Gets the name of the control tag. This property is used primarily by control developers.

Page 87: Best Tutorial of c#

TemplateControl Gets or sets a reference to the template that contains this control. (Inherited from

TemplateSourceDirectory Gets the virtual directory of the Page or UserControl that contains the current server control.

Text Gets or sets the text displayed in the validation control when validation fails.

ToolTip Gets or sets the text displayed when the mouse pointer hovers over the Web server control.from WebControl.)

Type Gets or sets the data type that the values being compared are converted to before the comparison is made.fromBaseCompareValidator.)

UniqueID Gets the unique, hierarchically qualified identifier for the server control.

ValidationGroup Gets or sets the name of the validation group to which this validation control belongs.

ViewState Gets a dictionary of state information that allows you to save and restore the view state of a server control across multiple requests for the same page. (Inherited from Control.)

ViewStateIgnoresCase Gets a value that indicates whether the StateBag object is case-insensitive.

ViewStateMode Gets or sets the view-state mode of this control. (Inherited from Control

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

Width Gets or sets the width of the Web server control. (Inherited from WebControl

http://msdn.microsoft.com/en-us/library/2s019wc0(v=VS.100).aspx

ASP.NET Login Controls Overview 

The ASP.NET login controls work together to provide for your ASP.NET Web applications a robust login solution that requires no programming. By default, login controls integrate with ASP.NET membership and forms authentication to help automate user authentication for your Web site. For information about using ASP.NET membership with forms authentication, see Introduction to Membership.

By default, the ASP.NET login controls work in plain text over HTTP. If you are concerned about security, use HTTPS with SSL encryption. For more information on SSL, see Configuring SSL on a Web Server or a Web Site in the IIS documentation.

Page 88: Best Tutorial of c#

Note

Login controls might not function properly if the Method of the ASP.NET Web page is

changed from POST (the default) to GET.

This topic describes each ASP.NET login control and provides links to the control's reference documentation.

The Login Control

The Login control displays a user interface for user authentication. The Login control contains text boxes for the user name and password and a check box that allows users to indicate whether they want the server to store their identity using ASP.NET membership and automatically be authenticated the next time they visit the site.

The Login control has properties for customized display, for customized messages, and for links to other pages where users can change their password or recover a forgotten password. The Login control can be used as a standalone control on a main or home page, or you can use it on a dedicated login page.

If you use the Login control with ASP.NET membership, you do not need to write code to perform authentication. However, if you want to create your own authentication logic, you can handle the Login control's Authenticate event and add custom authentication code.

Login Class

Note: This class is new in the .NET Framework version 2.0.

Provides user interface (UI) elements for logging in to a Web site.

Namespace: System.Web.UI.WebControlsAssembly: System.Web (in system.web.dll)

SYNTAX in VB

'Declaration

<BindableAttribute(False)> _Public Class Login

Inherits CompositeControl'Usage

Dim instance As Login

Page 89: Best Tutorial of c#

'Declaration

<BindableAttribute(False)> _Public Class Login

Inherits CompositeControl'Usage

Dim instance As Login

Syntax in C#:

[BindableAttribute(false)] public class Login : CompositeControl

Remarks

The Login control is a composite control that provides all the common UI elements needed to authenticate a user on a Web site. The following three elements are required for all login scenarios:

A unique user name to identify the user. A password to verify the identity of the user. A login button to send the login information to the server.

The Login control also provides the following optional UI elements that support additional functions:

A link for a password reminder. A Remember Me checkbox for retaining the login information between sessions. A Help link for users who are having trouble logging in. A Register New User link that redirects users to a registration page. Instruction text that appears on the login form. Custom error text that appears when the user clicks the login button without filling in

the user name or password fields. Custom error text that appears if the login fails. A custom action that occurs when login succeeds. A way to hide the login control if the user is already logged in to the site.

For a table showing which controls are required and which are optional, see LayoutTemplate property.

Security Note

Accepting user input is a potential security threat. Malicious users can send data that is

Page 90: Best Tutorial of c#

intended to expose vulnerabilities or run programs that try generated passwords. To

improve security when working with user input, you should use the validation features of

your control and secure any data providers that are configured for your control. For more

information, see Securing Login Controls, Basic Security Practices for Web Applications,

and Securing Membership.

The Login control uses a membership provider to obtain user credentials. Unless you specify otherwise, the Login control uses the default membership provider defined in the Web.config file. To specify a different provider, set the MembershipProvider property to one of the membership provider names defined in your application's Web.config file. For more information, see Membership Providers.

If you want to use a custom authentication service, you can use the OnAuthenticate method to call the service.

Styles and Templates

The appearance of the Login control is fully customizable through templates and style settings. All UI text messages are also customizable through properties of the Login class. The default interface text is automatically localized based on the locale setting on the server.

If the Login control is customized with templates, then the AccessKey property and the TabIndex property are ignored. In this case, set the AccessKey property and the TabIndex property of each template child control directly.

Login control properties represented by text boxes, such as UserName and Password, are accessible during all phases of the page life cycle. The control will pick up any changes made by the end user by means of the TextChanged event triggered by the textboxes.

Note

If you embed the Login control in a WizardStep object, explicitly set the ActiveStepIndex

property in a Page_Load event handler if the user is authenticated. The Wizard control

does not automatically advance to the next WizardStep object in this scenario.

The following table lists the Login control style properties and explains which UI element each style property affects. For a list of which properties each style applies to, see the documentation for the individual style properties.

Style property UI element affected

BorderPadding The space between the control contents and the control's border.

CheckBoxStyle Remember Me checkbox.

Page 91: Best Tutorial of c#

FailureTextStyle Login failure text.

InstructionTextS

tyle

Instructional text on the page that tells users how to use the control.

LabelStyle Labels for all input fields, such as text boxes.

TextBoxStyle Text entry input fields.

TitleTextStyle Title text.

ValidatorTextSty

le

Text displayed to the user when a login attempt is unsuccessful due to

validation errors.

HyperLinkStyle Links to other pages.

LoginButtonStyl

e

Login button.

Validation Groupings

The UserName and Password properties have RequiredFieldValidator controls associated with them to prevent users from submitting the page without providing required information.

The Login control uses a validation group so that other fields on the same page as the Login control can be validated separately. By default, the ID property of the Login control is used as the name of the validation group. For example, a Login control with the ID "Login1" will use a validation group name of "Login1". If you want to set the validation group that the Login control is part of, you must template the control and change the validation group name.

Inheritance Hierarchy

System.Object   System.Web.UI.Control     System.Web.UI.WebControls.WebControl       System.Web.UI.WebControls.CompositeControl        System.Web.UI.WebControls.Login

The LoginView Control

Page 92: Best Tutorial of c#

The LoginView control allows you to display different information to anonymous and logged-in users. The control displays one of two templates: the AnonymousTemplate or the LoggedInTemplate. In the templates, you can add markup and controls that display information appropriate for anonymous users and authenticated users, respectively.

The LoginView control also includes events for ViewChanging and ViewChanged, which allow you to write handlers for when the user logs in and changes status.

The LoginStatus Control

The LoginStatus control displays a login link for users who are not authenticated and a logout link for users who are authenticated. The login link takes the user to a login page. The logout link resets the current user's identity to be an anonymous user.

You can customize the appearance of the LoginStatus control by setting the LoginText and LoginImageUrl properties.

The LoginName Control

The LoginName control displays a user's login name if the user has logged in using ASP.NET membership. Alternatively, if your site uses integrated Windows authentication, the control displays the user's Windows account name.

The PasswordRecovery Control

The PasswordRecovery control allows user passwords to be retrieved based on the e-mail address that was used when the account was created. The PasswordRecovery control sends an e-mail message containing a password to the user.

You can configure ASP.NET membership to store passwords using non-reversible encryption. In that case, the PasswordRecovery control generates a new password instead of sending the original password to the user.

You can also configure membership to include a security question that the user must answer to recover a password. If you do, the PasswordRecovery control asks the question and checks the answer before recovering the password.

The PasswordRecovery control requires that your application can forward e-mail message to a Simple Mail Transfer Protocol (SMTP) server. You can customize the text and format of the e-mail message sent to the user by setting the MailDefinition property.

Note

Page 93: Best Tutorial of c#

Password information sent in an e-mail message is sent as clear text.

The following example shows a PasswordRecovery control declared in an ASP.NET page with MailDefinition property settings to customize the e-mail message.

Copy

<asp:PasswordRecovery ID="PasswordRecovery1" Runat="server"

SubmitButtonText="Get Password" SubmitButtonType="Link">

<MailDefinition From="[email protected]"

Subject="Your new password"

BodyFileName="PasswordMail.txt" />

</asp:PasswordRecovery>

The CreateUserWizard Control

The CreateUserWizard control collects information from potential users. By default, the CreateUserWizard control adds the new user to the ASP.NET membership system.

The CreateUserWizard control gathers the following user information:

User name Password Confirmation of password E-mail address Security question Security answer

This information is used to authenticate users and recover user passwords, if necessary.

Note

The CreateUserWizard control is inherited from the Wizard control.

The following example shows a typical ASP.NET declaration for the CreateUserWizard control:

Copy

<asp:CreateUserWizard ID="CreateUserWizard1" Runat="server"

Page 94: Best Tutorial of c#

ContinueDestinationPageUrl="~/Default.aspx">

<WizardSteps>

<asp:CreateUserWizardStep Runat="server"

Title="Sign Up for Your New Account">

</asp:CreateUserWizardStep>

<asp:CompleteWizardStep Runat="server"

Title="Complete">

</asp:CompleteWizardStep>

</WizardSteps>

</asp:CreateUserWizard>

The ChangePassword Control

The ChangePassword control allows users to change their password. The user must first supply the original password and then create and confirm the new password. If the original password is correct, the user password is changed to the new password. The control also includes support for sending an e-mail message about the new password.

The ChangePassword control includes two templated views that are displayed to the user. The first is the ChangePasswordTemplate, which displays the user interface used to gather the data required to change the user password. The second template is the SuccessTemplate, which defines the user interface that is displayed after a user password has been successfully changed.

The ChangePassword control works with authenticated and non-authenticated users. If a user has not been authenticated, the control prompts the user for a login name. If the user is authenticated, the control populates the text box with the user's login name.