Page Lifecycle Sample Code

Yesterday I attempted to create an ASP.NET page which used every single page event in order to better understand how to use each event. You cannot find any sample code for many page events. I managed to write code for every event except Page_AbortTransaction, Page_CommitTransaction, Page_DataBinding, and Page_Disposed which aren't being fired for this page. I tried to use meaningful examples but some of the code may be pointless. Let me know if you see any mistakes or have suggestions for improvements because this has gone into my notes.

The ASPX page includes a placeholder for adding a dynamic control and a GridView for experimenting with control rendering. I used the Northwind database for sample data. I also used a master page.

   1: <%@ Page Language="VB" MasterPageFile="~/Default.master" AutoEventWireup="false" CodeFile="LifeCycle.aspx.vb" Inherits="LifeCycle" title="ASP.NET 2.0 Life Cycle" %>
   2: <%@ MasterType VirtualPath="~/Default.master" %>
   3: <asp:Content ID="Content1" ContentPlaceHolderID="Main" Runat="Server">
   4:     <asp:PlaceHolder runat="server" id="LabelPlaceHolder" />
   5:     <br />
   6:     <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None">
   7:         <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
   8:         <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
   9:         <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
  10:         <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
  11:         <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
  12:         <EditRowStyle BackColor="#999999" />
  13:         <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
  14:     </asp:GridView>
  15: </asp:Content>

The VB code behind file uses a text file trace listener to log the page events as they are fired. That actually has to be set up in the web.config file. The Page_PreRenderComplete has some code commented out. This code adds the HTML rendered by the entire page to the log file but it causes an error about an extra form tag so I only left it in for debugging purposes. The only interesting things I'm doing is adjusting the column header text for the GridView and adding a top row. Some of the other page event code could use better examples.

   1: Imports System.Diagnostics
   2: Imports System.Data
   3: Imports System.Data.SqlClient
   4: Imports System.IO
   5:  
   6: Partial Class LifeCycle
   7:     Inherits System.Web.UI.Page
   8:  
   9:     Protected Sub Page_AbortTransaction(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.AbortTransaction
  10:         System.Diagnostics.Trace.WriteLine("Page_AbortTransaction " & Now())
  11:     End Sub
  12:  
  13:     Protected Sub Page_CommitTransaction(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.CommitTransaction
  14:         System.Diagnostics.Trace.WriteLine("Page_CommitTransaction " & Now())
  15:     End Sub
  16:  
  17:     Protected Sub Page_DataBinding(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.DataBinding
  18:         System.Diagnostics.Trace.WriteLine("Page_DataBinding " & Now())
  19:     End Sub
  20:  
  21:     Protected Sub Page_Disposed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Disposed
  22:         System.Diagnostics.Trace.WriteLine("Page_Disposed " & Now())
  23:     End Sub
  24:  
  25:     Protected Sub Page_Error(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Error
  26:         ' Use this event to log a page error
  27:         Dim objException As Exception = Server.GetLastError().GetBaseException()
  28:         System.Diagnostics.Trace.WriteLine(objException.ToString())
  29:         System.Diagnostics.Trace.WriteLine("Page_Error " & Now())
  30:     End Sub
  31:  
  32:     Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
  33:         ' Use this event to read or initialize control properties.
  34:         Dim ContentPlaceHolder1 As ContentPlaceHolder = CType(Master.FindControl("Main"), ContentPlaceHolder)
  35:         Dim LabelPlaceHolder As PlaceHolder = CType(ContentPlaceHolder1.FindControl("LabelPlaceHolder"), PlaceHolder)
  36:         Dim lblMessage As Label = CType(LabelPlaceHolder.FindControl("lblMessage"), Label)
  37:         lblMessage.ForeColor = Drawing.Color.Black
  38:         System.Diagnostics.Trace.WriteLine("Page_Init " & Now())
  39:     End Sub
  40:  
  41:     Protected Sub Page_InitComplete(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.InitComplete
  42:         ' Use this event for processing tasks that require all initialization be complete.
  43:         Dim ContentPlaceHolder1 As ContentPlaceHolder = CType(Master.FindControl("Main"), ContentPlaceHolder)
  44:         Dim LabelPlaceHolder As PlaceHolder = CType(ContentPlaceHolder1.FindControl("LabelPlaceHolder"), PlaceHolder)
  45:         Dim lblMessage As Label = CType(LabelPlaceHolder.FindControl("lblMessage"), Label)
  46:         lblMessage.ToolTip = "Tooltip added during InitComplete event."
  47:         ' Set a value in the viewstate
  48:         Me.ViewState("Author") = "Robert S. Robbins"
  49:         System.Diagnostics.Trace.WriteLine("Page_InitComplete " & Now())
  50:     End Sub
  51:  
  52:     Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
  53:         ' Use the OnLoad event method to set properties in controls and establish database connections.
  54:         Dim cn As New SqlConnection
  55:         Dim objSqlCommand As New SqlCommand
  56:         cn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("Northwind").ToString()
  57:         cn.Open()
  58:         objSqlCommand.Connection = cn
  59:         objSqlCommand.CommandText = "SELECT ProductID, ProductName, UnitPrice FROM Products ORDER BY ProductName"
  60:         Dim objDataSet As DataSet = New DataSet()
  61:         Dim objSqlDataAdapter As SqlDataAdapter = New SqlDataAdapter()
  62:         objSqlDataAdapter.SelectCommand = objSqlCommand
  63:         objSqlDataAdapter.Fill(objDataSet)
  64:         GridView1.DataSource = objDataSet
  65:         GridView1.DataBind()
  66:         cn.Close()
  67:         System.Diagnostics.Trace.WriteLine("Page_Load " & Now())
  68:     End Sub
  69:  
  70:     Protected Sub Page_LoadComplete(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.LoadComplete
  71:         ' Use this event for tasks that require that all other controls on the page be loaded.
  72:         ' Example: Get data from a GridView row after databinding has occurred.
  73:         System.Diagnostics.Trace.WriteLine(GridView1.Rows.Item(5).Cells(1).Text, "Row 6, Cell 2")
  74:         System.Diagnostics.Trace.WriteLine("Page_LoadComplete " & Now())
  75:     End Sub
  76:  
  77:     Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
  78:         ' Check the IsPostBack property to determine whether this is the first time the page is being processed.
  79:         If Page.IsPostBack = False Then
  80:             ' Create or re-create dynamic controls.
  81:             Dim lblMessage As New Label
  82:             lblMessage.ID = "lblMessage"
  83:             lblMessage.Width = 500
  84:             lblMessage.Text = "Dynamically created control."
  85:             Dim ContentPlaceHolder1 As ContentPlaceHolder = CType(Master.FindControl("Main"), ContentPlaceHolder)
  86:             Dim LabelPlaceHolder As PlaceHolder = CType(ContentPlaceHolder1.FindControl("LabelPlaceHolder"), PlaceHolder)
  87:             LabelPlaceHolder.Controls.Add(lblMessage)
  88:         End If
  89:         System.Diagnostics.Trace.WriteLine("Page_PreInit " & Now())
  90:     End Sub
  91:  
  92:     Protected Sub Page_PreLoad(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreLoad
  93:         ' Use this event if you need to perform processing on your page or control before the Load event.
  94:         ' Viewstate should be available now because it has been loaded.
  95:         System.Diagnostics.Trace.WriteLine(Me.ViewState.Values.Count, "ViewState Count")
  96:         ' The Request object should be available now. 
  97:         System.Diagnostics.Trace.WriteLine(Request.ServerVariables("SCRIPT_NAME"), "Script Name")
  98:         System.Diagnostics.Trace.WriteLine("Page_PreLoad " & Now())
  99:     End Sub
 100:  
 101:     Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
 102:         ' Use the event to make final changes to the contents of the page or its controls.
 103:         Dim ContentPlaceHolder1 As ContentPlaceHolder = CType(Master.FindControl("Main"), ContentPlaceHolder)
 104:         Dim GridView1 As GridView = CType(ContentPlaceHolder1.FindControl("GridView1"), GridView)
 105:         Dim objGridViewRow As GridViewRow
 106:         objGridViewRow = New GridViewRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal)
 107:         Dim objTableCell As TableCell = New TableCell()
 108:         Dim literal As LiteralControl = New LiteralControl()
 109:         literal.Text = "Northwind Products"
 110:         objTableCell.Controls.Add(literal)
 111:         objTableCell.ColumnSpan = 3
 112:         objTableCell.HorizontalAlign = HorizontalAlign.Center
 113:         objTableCell.ForeColor = Drawing.Color.White
 114:         objTableCell.BackColor = Drawing.Color.Black
 115:         objGridViewRow.Cells.Add(objTableCell)
 116:         GridView1.Controls(0).Controls.AddAt(0, objGridViewRow)
 117:         System.Diagnostics.Trace.WriteLine("Page_PreRender " & Now())
 118:     End Sub
 119:  
 120:     Protected Sub Page_PreRenderComplete(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRenderComplete
 121:         ' At this stage of the page life cycle, all controls are created, any pagination required is completed, and the page is ready to render to the output.
 122:         ' Example: The column headings of the gridview should be accessible now.
 123:         Dim ContentPlaceHolder1 As ContentPlaceHolder = CType(Master.FindControl("Main"), ContentPlaceHolder)
 124:         Dim GridView1 As GridView = CType(ContentPlaceHolder1.FindControl("GridView1"), GridView)
 125:         GridView1.HeaderRow.Cells(0).Text = "Product ID"
 126:         GridView1.HeaderRow.Cells(1).Text = "Product Name"
 127:         GridView1.HeaderRow.Cells(2).Text = "Unit Price"
 128:         ' Get the rendered HTML
 129:         'Dim objStringBuilder As New StringBuilder()
 130:         'Dim objStringWriter As New StringWriter(objStringBuilder)
 131:         'Dim objHtmlTextWriter As New HtmlTextWriter(objStringWriter)
 132:         'Me.RenderControl(objHtmlTextWriter)
 133:         'Dim strGridViewHTML As String = objStringBuilder.ToString()
 134:         'System.Diagnostics.Trace.WriteLine(strGridViewHTML)
 135:         System.Diagnostics.Trace.WriteLine("Page_PreRenderComplete " & Now())
 136:     End Sub
 137:  
 138:     Protected Sub Page_SaveStateComplete(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.SaveStateComplete
 139:         ' Use this event perform tasks that require view state to be saved, but that do not make any changes to controls.
 140:         ' Example: Lets store some extraneous information in the view state
 141:         Me.ViewState("Date") = Now()
 142:         System.Diagnostics.Trace.WriteLine("Page_SaveStateComplete " & Now())
 143:     End Sub
 144:  
 145:     Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
 146:         ' Use this event to do final cleanup work, such as closing open files and database connections, or finishing up logging or other request-specific tasks.
 147:         System.Diagnostics.Trace.WriteLine(Me.ViewState.Values.Count, "ViewState Count")
 148:         System.Diagnostics.Trace.WriteLine("Page_Unload " & Now())
 149:     End Sub
 150: End Class

 

13 Comments

Comments have been disabled for this content.