Friday 11 October 2013

How to access Previous Page control in next page

How to access Previous Page control in next page



<form id="form1" runat="server">
        <div>
            First Name:&nbsp;<asp:TextBox ID="FirstName" runat="server"></asp:TextBox><br />
            Last Name:&nbsp;<asp:TextBox ID="LastName" runat="server"></asp:TextBox><br /><br />
            <asp:Button ID="Button1" runat="server" Text="Submit To Destination Page"PostBackUrl="~/CrossPagePostbacks/DestinationPage.aspx" />
        </div>
    </form>


When our user clicks the Submit button, all the values from the HTML Form on SourcePage.aspx will be transfered to the DestinationPage.aspx and we will also be able to get reference to the SourcePage.aspx in our DestinationPage with the PreviousPage property like this:

So in our DestinationPage.aspx.cs code-behind we can easily access two TextBox controls on SourcePage.aspx and show them in two label controls like this:
    protected void Page_Load(object sender, EventArgs e)
    {
        // first check if we had a cross page postback
        if ( (PreviousPage != null) && (PreviousPage.IsCrossPagePostBack) )
        {
            Page previousPage = PreviousPage;
            TextBox firstName = (TextBox)previousPage.FindControl("FirstName");
            TextBox lastName = (TextBox)previousPage.FindControl("LastName");
            // we can now use the values from TextBoxes and display them in two Label controls..
            labelFirstName.Text = firstName.Text;
            labelLastName.Text = lastName.Text;
         }
    }


You probably noticed that we first checked if PreviousPage property of current page (DestinationPage.aspx) is NOT NULL, this is done to avoid running our code in case that user opens our DestinationPage.aspx directly, without running a cross page postback.

Also here we checked the another PreviousPage property called IsCrossPagePostBack to see if we really had a CrossPagePostback.
(If Server.Transfer is used to redirect to this page, IsCrossPagePostBack property will be set to FALSE.

TIP: We can be completely sure that we have a  real CrossPagePostback ONLY IF:
  1. Page.PreviousPage is NOT NULL,
  2. PreviousPage.IsCrossPagePostback is true

No comments:

Post a Comment