Passing data between aspx pages (part 1)

There are a number of  ways to pass information between aspx pages allowing you to collect data on one page and process on another. In part 1 we will learn the method that uses:
1. Server.Transfer control to send information to another page
2. PreviousPage.FindControl to receive it on another page.

The method uses an interesting mechanism that comes pre-installed in apsx pages and forms. This mechanism is based on event processing, included with each page (even the blank one). The developer can choose any event from page lifecycle (see http://www.asp.net/web-forms/videos/building-35-applications/page-lifecycle-events ) to put the code there that will execute when such event happens (fires). The example below shows code included in the Button_Click event on the sending page that triggers execution of the Server.Transfer control that send the form information to another page and also triggers that page loading (switching to it). Then you will see code (using PreviousPage.FindControl) that is  included into the Page_Load event that fires when the receiving page is loading (when no controls are shown yet, but some additional processing might take place).


Here is the code placed into Button1_Click event on the sending page that has a form with various controls and a button to trigger some action:

    Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles   Button1.Click        ' the code below sends form information to ANOTHER page (ASPXPage.aspx)
    Server.Transfer("ASPXPage.aspx")
    End Sub



Here is the code placed into the Page_Load event on the receiving page that later uses the information from the TextBox of the sending page to be shown in its own Label control:


Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If Not Page.PreviousPage Is Nothing Then


' preparing a variable ot accept a TextBox object from the form in the previous page

     Dim SourceTextBox As TextBox
' notice the use of PreviousPage.FindControl below
     SourceTextBox = CType(PreviousPage.FindControl("TextBox1"), TextBox)
     If Not SourceTextBox Is Nothing Then
        Label1.Text = SourceTextBox.Text
     End If
End If

    End Sub