.NET Tips and Tricks

Blog archive

Use PreviousPageType to Simplify Page Data Access

(Editor's Note: This article has been updated to correct errors in the code.)

In an earlier post on cross-page posting, a reader pointed out that I hadn't discussed the PreviousPageType directive, which can eliminate the need for using the awkward FindControl method (for more on the difficulties of using FindControl -- especially with pages using a Master Page -- see one of the first Practical ASP.NET columns I wrote). Here's how to use PreviousPageType.

In ASP.NET you can request another page either through cross-page posting, or through a Server.Transfer from the code in a different page and then accessing the original page from code in the new page. Let's call the page that makes the request the "source page" and call the requested page the "target page". In the Target page, you can use the Page's PreviousPage property to access the source page as an object, like this:

Dim pg As Page
pg = Me.PreviousPage

As my reader suggested, in the source page you can declare a public property that grabs a result from a control on the source page. This property, for instance, returns the Text property of a control called CustomerIDTextBox:

Public ReadOnly Property Customer() As String
      Return Me.CustomerIDTextBox.Text
    End Get
  End Property

However, the PreviousPage property returns a Page object; so, to access this property in the target page, you need to cast the PreviousPage property to the source page's type. Assuming that my source page is called Source.aspx, that code would look like this:

Dim CustomerID As String
CustomerID = CType(Me.PreviousPage, Source).CustomerID

If, as my reader points out, you know which page is going to be the source page, you can pass that information onto ASP.NET by adding the PreviousPageType directive to the aspx file of the target page. Since my source page is called Source.aspx, the directive in the target page that specifies the previous page would look like this:

<%@ Page  Language="VB" …
<%@  PreviousPageType VirtualPath="Source.aspx" %> 

This allows ASP.NET to strongly type the PreviousPage property in the target page. The code in my target page that accesses the property in the source page would now look like this:

Dim CustomerID As String
CustomerID = Me.PreviousPage.CustomerID

Posted by Peter Vogel on 03/12/2012

comments powered by Disqus


Subscribe on YouTube