PreviousPage Doesn't Work???

  • Thread starter Thread starter Jonathan Wood
  • Start date Start date
J

Jonathan Wood

In Microsoft Press' Introducing Microsoft ASP.NET 2.0, and also on sites
like http://msdn2.microsoft.com/en-us/library/ms178139.aspx, I've found a
number of examples that look something like this:

if (Page.PreviousPage != null)
{
TextBox SourceTextBox = (TextBox)PreviousPage.FindControl("TextBox1");
if (SourceTextBox != null)
{
Label1.Text = SourceTextBox.Text;
}
}

Yet, PreviousPage.FindControl always returns null for me. Using
PreviousPage.Title, I could verify that the previous page was the expected
page. But FindControl() isn't working.

I searched the Web but all I could really find is examples like the one
above, and posts where other people complained that this code does not work
for them either.

Any help?

Jonathan
 
PreviousPage.FindControl will only find controls at the page root. if
the control is a child of another then it will not find it.

you need to do a recursive search.

-- bruce (sqlwork.com)
 
Hi,

is TextBox perhaps contained in a another control (which would be a naming
container)?
 
I do have a few layers of <div> tags, if that's what you mean.

However, when I traverse the PreviousPage.Controls collection, the only one
that shows up is "ASP.default_master." None of the <div> tags seem to show
up, unless they would be "inside" the master--that doesn't make any sense.

Thanks.
 
That's the issue. The following code works:

protected String GetField(String field)
{
ContentPlaceHolder ph =
(ContentPlaceHolder)PreviousPage.Master.FindControl("ContentPlaceHolder1");
if (ph != null)
{
TextBox tb = (TextBox)ph.FindControl(field);
if (tb != null)
return tb.Text;
}
return String.Empty;
}

Thanks.
 
if you have a master page, then all the controls in the content are
children of the master (which is a control on the page).

the controls on a page are in a tree, the page has a control list, and
every control in that list has a list of controls. so, to find a
control, you need to find its parent, for which you need find its parent
until you get to the page.

if your control id is unique, you can just do a recursive search.

(note: air code)

Control myControl = DeepFind(Page,"myID");

Control DeepFind(Control parent, string id)
{
if (parent.ID == id)
return parent;
foreach (Control child in parent.Controls)
{
Control c = DeepFind(child,id);
if (c != null)
return c;

}
return null;
}

-- bruce (sqlwork.com)
 
Thanks. That is a more comprehensive approach to finding any control. Please
see my reply to David for the solution I ended up with.
 
Back
Top