Application |
HttpApplicationState = Page.Application |
Returns an instance of the HttpApplicationState class, which is the equivalent of the ASP intrinsic Application object. An instance of the HttpApplicationState class contains global information that can be shared across multiple sessions and requests within an ASP.NET application. For more information on the HttpApplicationState class and its members, see Chapter 13.
Parameters HttpApplicationState A variable of type HttpApplicationState that receives the instance of the HttpApplicationState class.
Example
The following code example uses Page object's Application property to add a name/value pair to the Application object and display the value in a label control. Since all of the properties of the Page object are exposed directly to any code associated with the page, it is not necessary to explicitly name the Page class (i.e., Page.Application) to access the Application property.
    Sub Page_Load( )
    	Application("Name") = "John Doe"
    	Message.Text = "The value <em>" &CStr(Application("Name")) &_
    		"</em> has been added to the Application collection."
    End Sub
Notes
Although you can retrieve a local object reference to the HttpApplicationState instance for the application, the more common use of this property is to access it directly through the Application property, as shown in the example.

Cache |
Cache = Page.Cache |
Returns an instance of the Cache class, which represents the cache for an application domain. Using the Cache property, data can be added to and retrieved from the cache.
Parameters Cache A variable of type Cache that will receive the Cache instance.
Example
The following code example adds two name/value pairs to the Cache object using the Cache property of the Page class and displays the values in a label control using the Page object's Cache property:
    Sub Page_Load(o As Object, e As EventArgs)
    	Cache("Name") = "John Doe"
    	Cache("Age") = 42
    	Message.Text = CStr(Cache.Item("Name"))& " is " &_
    		CStr(Cache("Age")) & " years old."
    End Sub
Notes
Like the Application object, the Cache object is more commonly accessed directly through the Cache property, rather than by obtaining a local object reference to the Cache instance for the application. Chapter 13 discusses when you might use the ASP.NET Cache rather than the Application state collection, and vice-versa. The Cache class includes the following members:
Cache member | Description
Add method | Adds an item to the cache
Count property | Indicates the number of items contained in the cache
Get method | Returns an object representing data in the cache with a particular key value
Insert method | Inserts an item into the cache and assigns it a key
Item property | Returns an object representing a cache item based on its key value or sets an item of data in the cache while assigning it a key value
Remove method | Removes an item with a particular key value from the cache

ClientTarget |
String = Page.ClientTarget |
Gets or sets a string value that allows you to override automatic browser detection in ASP.NET, force the page to be rendered for a browser type configured in machine.config or web.config, and specified by this property. The available preconfigured values for this property are: downlevel The page will be rendered based on the browser capabilities defined for unknown browsers in the <browserCaps> element of machine.config. ie4 value The page will be rendered based on the values for Internet Explorer 4.0 configured in the <browserCaps> element of machine.config. ie5 The page will be rendered based on the values for Internet Explorer 5.0 configured in the <browserCaps> element of machine.config.
Parameters String A string that specifies the alias for the browser capabilities that the page will target.
Example
The following code example initializes the ClientTarget property of the Page class to downlevel, indicating that ASP.NET must render the page for an unknown browser type, which will result in HTML 3.2-compliant output. The example then displays a message indicating whether a set of features is supported. In the case of downlevel, none of the listed features is supported.
    Sub Page_Load( )
    	Page.ClientTarget = "downlevel"
    		Message.Text= "Page is set to render for the " &_
    	Page.ClientTarget & " alias.<br/>"
    	Message.Text &= "Supported features:<br/>"
    	Message.Text &= "_JavaScript: " &_
    		Request.Browser.JavaScript & "<br/>"
    	Message.Text &= "- ActiveX Controls: " &_
    		Request.Browser.ActiveXControls & "<br/>"
    	Message.Text &= "- Frames: " &_
    		Request.Browser.Frames & "<br/>"
    End Sub
Notes
The ClientTarget can also be specified by using the ClientTarget attribute of the @ Page directive. Changing the value of the ClientTarget property in the example to ie4 will result in output indicating that all of the listed features are supported.
While most server controls render HTML 3.2 for all browsers, the validation controls are an example of controls that render differently, depending on the value of ClientTarget. If the ClientTarget property is set to downlevel, then validation is performed on the server side, meaning that if we view the source, no client-side script will perform the validation. If the ClientTarget is set to uplevel, then the validation controls emit client-side JavaScript to perform client-side validation.

Context |
HttpContext = Page.Context |
Returns an HttpContext instance containing context information for the current HTTP request.
Parameters HttpContext A variable of type HttpContext that will receive the reference to the current HttpContext instance.
Example
The following code example uses the Context property to return the name of the currently logged in user. This information is also available from the User property of the Page class, which is derived from the HttpContext associated with the current request.
    Sub Page_Load( )
    	Message.Text = "Currently logged in as: " &_
    		Context.User.Identity.Name
    End Sub
Notes
A common use of this property is to pass a reference to the HttpContext for the current request to a business object that needs access to the ASP.NET intrinsic objects (Request, Response, etc.). In addition to providing access to the Application, Request, Response, Server, and Session intrinsics, the HttpContext class provides access to the Trace and User information for the current HTTP request.

EnableViewState |
Boolean = Page.EnableViewState Page.EnableViewState = Boolean |
Returns or sets a Boolean value that indicates whether the Page maintains its view state and that of server controls it contains. The default value of this property is True, which means that the page maintains its view state.
Parameters Boolean A Boolean value that indicates whether the page maintains its view state.
Example
The following code example sets EnableViewState to False using the EnableViewState attribute of the @ Page directive and displays its value on the page:
    <%@ Page Language="vb" EnableViewState="True" %>
    <html>
    	<head>
    		<title></title>
    		<script runat="server">
    			Sub Page_Load( )
    				If Page.EnableViewState = True Then
    					Message.Text ="ViewState is enabled."
    				Else
    					Message.Text = "ViewState is disabled."
    				End If
    			End Sub
    		</script>
    	</head>
    <body>
    	<form runat="server">
    		<asp:label id="Message" runat="server"/>
    	</form>
    </body>
    </html>
Notes
The EnableViewState property can also be specified using the EnableViewState attribute of the @ Page directive, as shown in the example. Examining a page's HTML source using a browser's View Source feature shows the effect of the EnableViewState property. If the EnableViewState property is set to False, the source will look similar to:
    <input type="hidden" name="_ _VIEWSTATE"
    	value="dDwxMDA3MzE2MzEyOzs+"/>
If the EnableViewState property is set to True, the source will look similar to:
    <input type="hidden" name="_ _VIEWSTATE"
    	value="dDwxMDA3MzE2MzEyO3Q8O2w8aTwxPjs+O2w8dDw7bDxpPDM+Oz47bDx0PHA8cDxsPF
    	RleHQ7PjtsPFZhbHVlIG9mIHRoZSBFbmFibGVWaWV3U3RhdGUgcHJvcGVydHkgaXMgVHJ1ZTs
    	+Pjs+Ozs+Oz4+Oz4+Oz4=" />
The extra characters in the value of the _ _VIEWSTATE hidden field indicate the view state of the current page. The view state of a page includes the transient properties of server controls, such as BackColor or ForeColor. Note that pages that do not contain a <form> element with the runat="server" attribute will not save view state, regardless of the value of the EnableViewState property.

ErrorPage |
String = Page.ErrorPage Page.ErrorPage = String |
Returns or sets the name of the page to redirect to in the event of an unhandled page exception.
Parameters String A String value that indicates the name of the page to redirect to in the event of an unhandled page exception.
Example
The example below changes the ErrorPage property and shows that executed page when an unhandled exception occurs in the page:
    Sub Page_Load( )
    	Page.ErrorPage = "ErrorPage_Handler.aspx"
    	Dim x, y, overflow As Integer
    	x = 1
    	y = 0
    	overflow = x/y
    	'This code will not be executed
    	Message.Text = "Error Page is " & Page.ErrorPage & "."
    End Sub
The Page_Load for ErrorPage_Handler.aspx is shown below:
    Sub Page_Load( )
    	Message.Text = "We're sorry. An error occurred during the" &_
    		" processing of your request. Please try again later."
    End Sub
Notes
The ErrorPage property can also be specified using the ErrorPage attribute of the @ Page directive.

IsPostBack |
Boolean = Page.IsPostBack |
Returns a Boolean value that indicates if the page is loaded for the first time (False) or is loaded as a result of the client postback (True). This property comes handy for the logic that needs to be executed the first time the page is executed or every time the page is posted back to itself, depending on how you structure your If statement.
Parameters Boolean A Boolean value that indicates if the page is loaded for the first time or is loaded as a result of the client postback.
Example
The code example below uses the IsPostBack property to display different messages in the Label control, depending on whether the page is loaded for the first time or is loaded as a result of the client postback. The first time the page is loaded, the IsPostBack property returns False, causing the string "Non-PostBack" to be displayed. Clicking the button posts the page back to itself, causing IsPostBack to return True and the string "PostBack" to be displayed.
    <%@ Page Language="vb" %>
    <html>
    	<head>
    		<title></title>
    		<script runat="server">
    			Sub Page_Load( )
    				If Page.IsPostBack Then
    					Message.Text = "PostBack"
    				Else
    					Message.Text = "Non-PostBack"
    				End If
    			End Sub
    		</script>
    	</head>
    <body>
    	<form runat="server">
    		<asp:button id="post" Text="Post page" runat="server"/>
    		<asp:label id="Message" runat="server"/>
    	</form>
    </body>
    </html>
Notes
The IsPostBack property will return True only for pages that contain a <form> element with the runat="server" attribute and at least one control that causes a postback. This can be a Button control, as shown in the example, or another control, such as a DropDownList control, whose AutoPostBack property is set to True.

IsValid |
Boolean = Page.IsValid |
ReturnsIs a Boolean value, indicating whether any validation controls on the page were unable to successfully validate user input.
Parameters Boolean A Boolean indicating whether the validation succeeded.
Example
The example uses the IsValid property to determine whether validation on the current page succeeded, and displays a message:
    <%@ Page Language="vb" %>
    <html>
    	<head>
    		<title></title>
    		<script runat="server">
    			Sub Page_Load( )
    				If IsPostBack Then Page.Validate()
    					If Page.IsValid Then
    						Message.Text = "Page is valid."
    					Else
    						Message.Text = "Page is not valid."
    					End If
    				End If
    			End Sub
    		</script>
    	</head>
    <body>
    	<form runat="server">
    	    Enter your name:
    		<asp:textbox id="name" runat="server"/>
    		<asp:requiredfieldvalidator
    			id="rfvName"
    			controltovalidate="name"
    			enableclientscript="false"
    			errormessage="Required!"
    			runat="server"/>
    		<br/>
    		<asp:button id="submit" Text="Submit" runat="server"/>
    		<br/>
    		<asp:label id="Message" runat="server"/>
    	</form>
    </body>
    </html>
Notes
The IsValid property determines whether the overall validation performed by a form's validator controls has succeeded. If the page has no validator controls, the property's value is always True. Before checking the value of IsValid, you must either call the Page.Validate method, as shown in the example, or have submitted the page with a control (such as a Button, ImageButton, or LinkButton control) whose CausesValidation property is set to True. Otherwise, an exception will occur.
In the example, the EnableClientScript property of the RequiredFieldValidator control is set to False, which disables client-side validation. By default, client-side validation is enabled and the page is never submitted to the server if the validation fails. Uplevel browsers perform validation on the client using client-side scripts, and only when validation succeeds is the page submitted. Only when the page is submitted is the server-side event handler code executed and the message displayed based on the value of the IsValid property.
Checking the IsValid property is important whether client-side validation is enabled, since a malicious client could bypass client-side validation.

Request |
HttpRequest = Page.Request |
Returns an instance of the HttpRequest class class that allows us to access data from the incoming HTTP requests. It's the equivalent of the ASP intrinsic Request object. For more information on the HttpRequest class, see Chapter 16.
Parameters HttpRequest An object of type HttpRequest that contains the data from the incoming HTTP requests.
Example
The following code example uses the ServerVariables collection of the HttpRequest object to display the IP address of the client making the request:
    Sub Page_Load( )
    	Message.Text = "The current request is from: " &_
    		CStr(Request.ServerVariables.Item("REMOTE_ADDRESS"))
    End Sub
Notes
As with the Application and Cache properties, while you can retrieve a local reference to the HttpRequest instance associated with the request, it is more common to access this instance directly through the Request property, as shown in this example.

Response |
HttpResponse = Page.Response |
Returns an instance of the HttpResponse class that stores information about the response and allows us to send HTTP response data to a browser. It's the equivalent of the ASP intrinsic Response object. For information on the HttpResponse class, see Chapter 17.
Parameters HttpResponse An object of type HttpResponse that receives the instance of the HttpResponse class.
Example
The following example uses the Response property of the page object to set the ContentType property of the HttpResponse class to text/xml. Setting this property will result in the output of the page being displayed as XML markup in Internet Explorer 5.0 or above.
    Sub Page_Load( )
    	Response.ContentType = "text/xml"
    	Message.Text = "This page will be displayed as XML in " &_
    		"Internet Explorer 5.0 or above."
    End Sub
Notes
As with the Application and Cache properties, while you can retrieve a local reference to the HttpResponse instance associated with the request, it is more common to access this instance directly through the Request property, as shown in this example.

Server |
HttpServerUtility = Page.Server |
Returns an instance of the HttpServerUtility class, which exposes useful methods for working with ASP.NET requests. For more information on the HttpServerUtility class, see Chapter 18.
Parameters HttpServerUtility An object of type HttpServerUtility that may be used to access useful properties and methods exposed by this class.
Example
The following code example uses the Server property to access the HtmlEncode method of the HttpServerUtility class, which allows you to encode HTML tags and characters so that they will be displayed to the user, rather than interpreted and rendered by the browser:
    Sub Page_Load( )
    	Message.Text = Server.HtmlEncode("<em>Hello, World!</em>")
    End Sub
The HTML rendered from this page would look like the following:
    <html>
    	<head>
    		<title> Server property example </title>
    	</head>
    <body>
    	<span id="Message">&lt;em&gt;Hello,World!&lt;/em&gt; </span>
    </body>
    </html>
Notes
As with the Request and Response properties, while you can retrieve a local reference to the HttpServerUtility instance associated with the application, it is more common to access this instance directly through the Server property, as shown in this example.

Session |
HttpSessionState = Page.Session |
Returns an object that represents the current user session. A Session object is maintained for each user that requests a page from an ASP.NET application. You can store session-specific data in the Session object and then access it across multiple pages in an ASP.NET application. For more information on the HttpSessionState class, see Chapter 19.
Parameters HttpSessionState An HttpSessionState object that represents the current user session.
Example
The example uses the Session object to display the value of the Mode property, which indicates where session state information is stored:
    Sub Page_Load( )
    	Message.Text = "Current Session State Mode: " &_
    			Session.Mode.ToString( )
    End Sub
Notes
As with the Request and Response properties, while you can retrieve a local reference to the HttpSessionState instance associated with the request, it is more common to access this instance directly through the Session property, as shown in this example.

SmartNavigation |
Boolean = Page.SmartNavigation Page.SmartNavigation = Boolean |
Returns or sets a Boolean indicating whether the SmartNavigation feature is turned on. The SmartNavigation feature, which is compatible only with Internet Explorer, uses <iframe> elements to allow only portions of the page to be refreshed when the page is posted back. This can help eliminate the annoying visual flicker associated with postbacks.
Parameters Boolean A Boolean value that indicates whether or not SmartNavigation is enabled.
Example
The following code example sets the SmartNavigation property to True using the SmartNavigation attribute of the @ Page directive. When the page is posted back, only the current page will be stored in the browser's history, so the Back button will be disabled.
    <%@ Page Language="vb" SmartNavigation="True" %>
    <html>
    	<head>
    		<title> SmartNavigation property example </title>
    		<script runat="server">
    			Sub Page_Load( )
    				Message.Text = "This Label will change."
    				Message2.Text = "This Label will not change."
    			End Sub
    			Sub UpdateLabel(Sender As Object, e As EventArgs)
    				Message.Text = "This Label has changed."
    			End Sub
    		</script>
    	</head>
    <body>
    	<form runat="server">
    		<asp:label id="Message" runat="server"/>
    		<asp:button id="update"
    			onClick="UpdateLabel"
    			text="Click to update label text"
    			runat="server"/>
    	</form>
    	<asp:label id="Message2" runat="server"/>
    </body>
    </html>
Notes
In addition to eliminating flicker when navigating or posting back, SmartNavigation maintains the current scroll position when a page is posted back and maintains only a single page in the browser's history, which prevents users from clicking the browser's Back button to go to a previous state of the page. While you can set this property from code, it is recommended that this property be set using the SmartNavigation attribute of the @ Page directive, as shown in this example.

Trace |
TraceContext = Page.Trace |
Returns the TraceContex object for the current web request. Tracing provides the details about the execution of the web request. The TraceContext class includes the following members:
Member | Description
IsEnabled | Indicates whether tracing is enabled for the current page.
TraceMode | A member of the TraceMode enumeration that indicates how items should be sorted. Possible values are SortByCategory and SortByTime. The latter is the default value defined in machine.config.
Warn method | Writes a message to the trace log using red text.
Write method | Writes a message to the trace log.
Parameters TraceContext An instance of the TraceContext class.
Example
The example turns tracing on programmatically by using the Trace property of the Page class:
    Sub Page_Load( )
    	If Trace.IsEnabled = True Then
    		Message.Text = "Tracing is enabled."
    	Else
    		Message.Text = "Tracing is not enabled."
    	End If
    End Sub
Notes
As with the Request and Response properties, while you can retrieve a local reference to the TraceContext instance associated with the request, it is more common to access this instance directly through the Trace property, as shown in the following example. For more information on application tracing, see Chapter 10.

User |
IPrincipal = Page.User |
Returns an instance of an object implementing the IPrincipal interface containing security information about the user making the page request. The IPrincipal interface implements the following members:
Member | Description
Identity property | Returns the IIdentity object representing the user requesting the page
IsInRole property | Indicates whether the user requesting the page is in a particular role
Parameters IPrincipal An object variable that implements IPrincipal.
Example
The example obtains the user's authentication status and name using the User property and displays it in the browser:
    Sub Page_Load( )
    	Message.Text = "Authenticated: " &_
    		User.Identity.IsAuthenticated & "<br/>"
    	Message.Text &= "User Name: " & User.Identity.Name
    End Sub
Notes
In order for the IPrincipal object returned by the User property to be populated, some form of authentication must be configured in either machine.config or web.config, and at a minimum, an authorization rule must be configured that excludes anonymous users. If these conditions are not met, the IsAuthenticated property of the IIdentity object will return False and the Name property will return an empty string.

ViewState |
StateBag = Page.ViewState |
The ViewState property returns an instance of the StateBag class containing state information for server controls on the page. This StateBag instance can also be used to store arbitrary data that needs to be preserved across multiple requests for the same page.
Parameters StateBag An object of type StateBag that contains the property values for server controls on the page. This StateBag instance can also be used to store arbitrary data that needs to be preserved across multiple requests for the same page.
Example
The following code example sets the ForeColor property of the Message control, and then stores the value of that color in the ViewState StateBag instance. If the page is posted back, the code retrieves the color that was stored, and depending on the name of the color, changes the color from Red to Black, or vice-versa.
    <%@ Page Language="vb" %>
    <html>
    	<head>
    		<title>ViewState property example</title>
    		<script runat="server">
    			Sub Page_Load()
    				Dim LocalColor As System.Drawing.Color
    				If IsPostBack Then
    					LocalColor = CType(ViewState("LabelColor"),_
    						System.Drawing.Color)
    					If LocalColor.Name = "Black" Then
    						LocalColor = System.Drawing.Color.Red
    					Else
    						LocalColor = System.Drawing.Color.Black
    					End If
    					Message.ForeColor = LocalColor
    					Message.Text = "Label color is " & LocalColor.Name ViewState("LabelColor") = LocalColor
    				Else
    					Message.ForeColor = System.Drawing.Color.Black
    					LocalColor = Message.ForeColor
    					Message.Text = "Label color is " & LocalColor.Name ViewState("LabelColor") = LocalColor
    				End If
    			End Sub
    		</script>
    	</head>
    <body>
    	<form runat="server">
    		<asp:button id="button"
    			text="Click to change label color"
    			runat="server"/>
    		<asp:label id="Message" runat="server"/>
    	</form>
    </body>
    </html>
Notes
ViewState, in addition to managing state for server controls automatically, is a convenient place for ambient page state that needs to be maintained from request to request. In addition to storing primitive data types such as integers and strings, the StateBag class can be used to store objects, as long as those objects support serialization, as does the Color structure in the example. When you store an object that supports serialization in ViewState, the object's state is automatically serialized into a form that can be stored in ViewState and deserialized into an object instance when you reference the object again.
Because ViewState does not store type information with the object, you must cast the object retrieved from ViewState to the correct type. In the case of the example, this type is System.Drawing.Color. Finally, think carefully before storing large objects (such as datasets) in ViewState. Because ViewState is stored as a hidden form field, it is sent to the browser with each request. Storing large objects in ViewState will result in slower page load times.

Controls |
ControlCollection = Page.Controls |
Provides access to the ControlCollection instance associated with the page, with which you can add or manipulate controls at runtime.
Parameters ControlCollection An object of type ControlCollection containing the controls associated with the page.
Example
The code example uses the Controls property to display the Count property of the ControlCollection class instance associated with the page. It then adds a new Label control to the collection and displays the updated Count property by using the new label.
    Sub Page_Load( )
    	Message.Text = "There are currently " & Controls.Count &_
    		" controls on the page.<br/>"
    	Dim Message2 As New Label
    	Controls.AddAt(Controls.Count - 1, Message2)
    	Message2.Text = "There are now " & Controls.Count &_
    		" controls on the page."
    End Sub
Notes
As with the Session and Trace properties, while you can retrieve a local reference to the Controls collection associated with the page, it is more common to access this instance directly through the Controls property, as shown in the example.
Note that when adding a control to a page that already contains controls, using the AddAt method of the ControlCollection class allows more precise placement of the control when compared to the Add method, which simply places the control at the end of the collection. In the example, using the Add method would result in the output from the added Label control appearing after the page's closing </html> tag, which is not well-formed HTML and could cause the page to render incorrectly in some browsers.

Validators |
ValidatorCollection = Page.Validators |
Returns an instance of the ValidatorCollection class containing all the validator controls contained on the requested page. We can access each validator control by iterating the ValidatorCollection collection.
Parameters ValidatorCollection An object variable of type ValidatorCollection.
Example
The code example displays a Textbox control with a RequiredFieldValidator and RegularExpressionValidator control assigned to it. In Page_Load, the code iterates through the ValidatorCollection returned by the Validators property and displays the ID and ErrorMessage property of each validator in the collection:
    <%@ Page Language="vb" %>
    <html>
    	<head>
    		<title></title>
    		<script runat="server">
    			Sub Page_Load( )
    				Dim Validator as BaseValidator
    				For Each Validator in Validators
    					Message.Text &= Validator.ID & " error message: "
    					Message.Text &= Validator.ErrorMessage & "<br/>"
    				Next
    			End Sub
    		</script>
    	</head>
    <body>
    	<form runat="server">
    			Phone: <asp:textbox id="phone" runat="server"/>
    			<asp:requiredfieldvalidator
    				id="rfvPhone"
    				controltovalidate="phone"
    				display="dynamic"
    				errormessage="Required!"
    				runat="server"/>
    			<asp:regularexpressionvalidator
    				id="revPhone"
    				controltovalidate="phone"
    				display="dynamic"
    				validationexpression="^[2-9]\d{2}-\d{3}-\d{4}$"
    				errormessage="Enter a phone number in the form xxx-xxx-xxxx"
    				runat="server"/>
    		<br/>
    		<asp:button id="submit" text="Submit" runat="server"/>
    	</form>
    	<br/>
    	<asp:label id="Message" runat="server"/>
    </body>
    </html>
Notes
Because we are displaying only properties from the validator controls that are inherited from the BaseValidator control (from which all validation controls are derived), we don't need to cast the validator to its specific type before accessing the properties. If, however, we wanted to display a property that was specific to the type of validator used (such as the ValidationExpression property of the RegularExpressionValidator class), we would need to cast the control to the correct type. In Visual Basic .NET, this is done using the CType keyword.

DataBind |
Page.DataBind( ) |
Evaluates and resolves any data binding expressions in the page. It also calls DataBind on all child controls.
Parameters
None
Example
The following code example uses a data binding expression to set the ForeColor attribute of a label control tag to the value of local variable named color. When the DataBind method is called in Page_Load, the value of the Color variable is assigned to the ForeColor attribute (which is effectively the same as setting the ForeColor property in code):
    <%@ Page Language="vb" %>
    <html>
    	<head>
    		<title></title>
    		<script runat="server">
    			Dim Color As System.Drawing.Color = System.Drawing.Color.Red
    			Sub Page_Load( )
    				Message.Text = "ForeColor is: " & Color.Name DataBind( )
    			End Sub
    		</script>
    	</head>
    <body>
    	<asp:label id="Message"ForeColor="<%# Color %>"runat="server"/>
    </body>
    </html>
Notes
If you want to perform data binding on a specific control on the page, such as a DataGrid or DataList control, it may be more efficient to call DataBind on that control rather than on the page, since calling it on the control will avoid any overhead in calling DataBind on controls for which data binding is not needed.

FindControl |
Control = Page.FindControl(String) |
Returns a reference to the control object whose name corresponds to a search string. The FindControl method is a member of the base Control class.
Parameters Control An instance of the Control class that represents the control that is found using the FindControl method. This control must be cast to the correct control type to access members that are specific to the control type. String A string containing the programmatic identifier of the control. This value is the same as the ID attribute of a declarative control, or in the case of controls created at runtime, is the same as the object name defined for the control.
Example
The example finds a control using its ID and changes its background color:
    Sub Page_Load( )
    	Dim TheControl As Control = FindControl("Message")
    	If Not TheControl Is Nothing Then
    		Dim TheLabel As Label = CType(TheControl,Label)
    		TheLabel.Text = "Found the label named Message!"
    		TheLabel.BackColor = System.Drawing.Color.Blue
    	End If
    End Sub
Notes
The FindControl method, which is inherited from the Control class (from which the Page class is derived), is useful when dealing with nested controls or user controls that need to manipulate a control in their parent page. For example, code in a user control could call FindControl on the page containing the user control to locate and manipulate a control contained within the page (but outside the user control).

HasControls |
Boolean = Page.HasControls( ) |
Returns a Boolean value that indicates whether the page contains child controls.
Parameters Boolean A Boolean value that indicates whether the page contains child controls.
Example
The code example displays a message indicating whether the page has controls in its Controls collection, based on the value returned by HasControls:
    Sub Page_Load( )
    	If Page.HasControls = True Then
    		Message.Text = "The page contains controls."
    	Else
    		Message.Text = "The page does not contain controls."
    	End If
    End Sub

LoadControl |
objControl = Page.LoadControl(strPath) |
Returns an instance of the user control defined in the strPath user control file. This allows dynamic loading of user controls instead of using the @ Register directive.
Parameters objControl An object of type Control that represents the user control specified in the given path. strPath The virtual path to a user control file.
Example
The example uses the LoadControl to load a user control at runtime and adds it to the page's Controls collection:
    Sub Page_Load( )
    	Dim Hello As UserControl = LoadControl("hello.ascx")
    	Page.Controls.Add(Hello)
    End Sub
The user control hello.ascx is as follows:
    <h1>Hello, World!</h1>

MapPath |
String = Page.MapPath(virtualPath) |
Returns the physical path that corresponds to a given virtual path.
Parameters String A String containing the physical path that corresponds to virtualPath. virtualPath A string containing an absolute or relative virtual path.
Example
The example maps the virtual path of the named page to its physical path:
    Sub Page_Load( )
    	Message.Text = MapPath("MapPath.aspx")
    End Sub
Notes
The Page.MapPath method duplicates the functionality of the Server.MapPath method.

ResolveUrl |
String = Page.ResolveUrl(strRelativeUrl) |
Returns an absolute URL corresponding to a relative URL.
Parameters String A string containing the absolute URL. strRelativeUrl A relative URL.
Example
The example maps the current relative URL to an absolute URL:
    Sub Page_Load( )
    	Message.Text = Page.ResolveUrl("ResolveUrl.aspx")
    End Sub

Validate |
Page.Validate( ) |
Invokes the validation logic for each validator control on the page. When this method is invoked, it iterates the Page object's ValidatorCollection collection and executes the validation logic associated with each validator control.
Example
See the example for the IsValid property.
Notes
The Validate method is called automatically when the user clicks any HTML or ASP button control whose CausesValidation property is True.

Error |
Sub Page_Error(Sender As Object, e As EventArgs) 'error handling code End Sub |
The Error event is fired when an unhandled exception occurs on the page. If no event handler is defined for this event, the Application_Error event is fired. If the exception is still not handled, control is passed to the page (or pages) defined in the<customErrors> element<customErrors> element in web.config.
Parameters Sender An argument containing information about the object that raised the event. e An object of type EventArgs containing additional information about the event.
Example
The following code example deliberately causes an overflow exception and then handles that exception in the Page_Error handler, displaying the text of the exception and then clearing it:
    Sub Page_Load( )
    	Dim x, y, overflow As Integer
    	x = 1
    	y = 0
    	overflow = x / y
    End Sub

    Sub Page_Error( )
    	Response.Write(Server.GetLastError.ToString())
    	Server.ClearError
    End Sub
Notes
The current exception is obtained using the GetLastError method of the Server class. Once you've finished with your error handling, you can either clear the exception by calling Server.ClearError, as shown in the example, or allow the exception to bubble up to the next level of error handling. Note that the Sender and e arguments are optional for this event, as shown in the example. When the AutoEventWireup attribute of the @ Page directive is set to True (the default), ASP.NET will automatically call the event handler for this event, as long as it has the correct Page_Error signature.

Init |
      Sub Page_Init(Sender As Object, e As EventArgs) 'initialization code
      End Sub
Parameters Sender An argument containing information about the object that raised the event. e An object of type EventArgs containing additional information about the event.
Example
The code example initializes a variable for setting the ForeColor property of a label in Page_Init, and then modifies that value to set the ForeColor property of another label in Page_Load:
    <%@ Page Language="vb" %>
    <html>
    	<head>
    		<title> Init event example </title>
    		<script runat="server">
    			Dim TheColor As System.Drawing.Color
    			Sub Page_Init( )
    				TheColor = System.Drawing.Color.Red
    			End Sub
    			Sub Page_Load( )
    				Message.ForeColor = TheColor
    				Message.Text = "The color of the text was set in Page_Init."
    				TheColor = System.Drawing.Color.Blue
    				Message2.ForeColor = TheColor
    				Message2.Text = "The color of the text was set in Page_Load."
    			End Sub
    		</script>
    	</head>
    <body>
    	<asp:label id="Message" runat="server"/>
    	<br/>
    	<asp:label id="Message2" runat="server"/>
    </body>
    </html>
Notes
Note that the Sender and e arguments are optional for this event, as shown in the example. When the AutoEventWireup attribute of the @ Page directive is set to True (the default), ASP.NET will automatically call the event handler for this event, as long as it has the signature Page_Init.

Load |
    Sub Page_Load(Sender As Object, e As EventArgs) 'code
    End Sub
Fired when the page is loaded. Since this event is fired on every page request, we can add any initialization code that needs to be executed at the page level, including the initialization of the page's child controls. When the Load event fires, the page's view state information is also accessible.
The Load event is passed the following arguments by ASP.NET: Sender An argument containing information about the object that raised the event. e An object of type EventArgs containing additional information about the event.
Example
See the example for Init.
Notes
Note that the Sender and e arguments are optional for this event, as shown in the example. When the AutoEventWireup attribute of the @ Page directive is set to True (the default), ASP.NET will automatically call the event handler for this event, as long as it has the correct Page_Load event signature.

Unload |
    Sub Page_Unload(Sender As Object, e As EventArgs) 'cleanup code
    End Sub
Fired when the page is unloaded from memory. Since this event is fired before the page is unloaded, we can perform cleanup operations, such as closing open files and database connections.
The Unload event is passed the following arguments by ASP.NET: Sender An argument containing information about the object that raised the event. e An object of type EventArgs containing additional information about the event.
Example
The example demonstrates the Unload event by closing a file that was opened for display in the Page_Load event handler:
    Dim TheFile As System.IO.StreamReader
    Sub Page_Load( )
    	TheFile = System.IO.File.OpenText(MapPath("Init.aspx"))
    	Message.Text = "<pre>" &_
    		Server.HtmlEncode(TheFile.ReadToEnd()) & " </pre>"
    End Sub

    Sub Page_Unload( )
    	TheFile.Close( )
    End Sub
Notes
While the Unload event is useful for performing page-level cleanup tasks, for resources such as databases, for which it is possible that an exception will interrupt the normal flow of page processing, it may be better to place the cleanup code for that resource in the Finally block of a Try...Catch...Finally statement, which will ensure that the cleanup code is always executed. For more information on Try...Catch...Finally, see Chapter 10. Note that the Sender and e arguments are optional for this event, as shown in the example. When theAutoEventWireup attribute of the @ Page directive is set to True (the default), ASP.NET will automatically call the event handler for this event, as long as it has the signature Page_Unload.