Name
Unload
Synopsis
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 the AutoEventWireup
attribute of the
@ Page
directive is set to True
(the default), ASP.NET ...
Get ASP.NET in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.