Amadiere.com

Fourteen and a half crazy frog burpers

21st May 2009

Cross-page PostBack’s and Master Pages

Filed under: ASP.NET — Tags: , , — Alex Holt @ 6:39 pm

I’ve been a developer for a long time in PHP and Classic ASP, recently, we’ve been picking up the ASP.NET baton and running with it. We’re not running very fast it has to be said. It’s more a running the hundred metres with 100′s of rakes scattered across your track.

I digress. We came across a problem and boy did it stump us. We were trying to use Webforms to submit a POST to another Webforms page. We had our trusty copy of ASP.NET 3.5 Professional, but its example wasn’t working in our page. We took it out and placed it into a sandbox, sure enough it was fine and dandy. We eventually bottomed it to be something to do with the Master Page and after examining the Site.master file for any obvious errors we were stumped.

Basically, the book says to do a standard CrossPage PostBack you do the following:

using System;
using System.Web.UI.WebControls;
 
public partial class DestinationPage : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
    if (PreviousPage != null && PreviousPage.IsCrossPagePostBack)
    {
      TextBox text = PreviousPage.FindControl("TextBox1") as TextBox;
      if (text != null)
      {
         Label1.Text = text.Text;
      }
    }
  }
}

This didn’t work quite because the PreviousPage was the Master and the Master doesn’t directly contain the TextBox1. Therefore, before we can access this property, we must create an access point to the ContentPlaceHolder via something like:

ContentPlaceHolder ContentPH1 = (ContentPlaceHolder)PreviousPage.Master.FindControl("ContentPlaceHolder1");

This worked a treat, we were then able to access our TextBox1 via that control.

TextBox text = ContentPH1.FindControl("TextBox1") as TextBox;

This may seem a very trivial question, but it caused no ends of problems because the searches we found were never clearly the scenario we had. Therefore, I’m actively writing this post to reverse that injustice and hope that someone, at somepoint, finds it useful!

Leave a comment

Theme designed & built for Amadiere.com by Alex Holt. Powered by WordPress