You should have titled this question "How do I find a control in a ContentPlaceholder
?", because your problem is not that PreviousPage
doesn't work, it's that you don't understand how ContentPlaceholder
s work.
This problem has nothing to do with a master page per se, and is entirely related to using a ContentPlaceholder
, which is a Naming Container in asp.net parlance. FindControls
does not search inside Naming Containers, which is exactly how they are designed.
PreviousPage
works fine with master pages, thus my confusion about what they have to do with your problem. You can access any property on the previous page that you want, and it will in fact work. For example:
HtmlForm form = PreviousPage.Form; // this works fine
Control ctrl = PreviousPage.Master.FindControl("TextBox1"); // this works as well
The problem you are likely encountering is that you're trying to use FindControl()
to find a specific control in the content page, and it's not working, precisely because you're calling FindControl on the PreviousPage, and not on the naming container that the control you're looking for exists in.
To find the control you want, you just have to do a FindControl
on the naming container. The following code works fine, assuming the placeholder is named ContentPlaceHolder1.
var ph = PreviousPage.Controls[0].FindControl("ContentPlaceHolder1");
var ctl = ph.FindControl("TextBox1");
You can verify that this problem has nothing to do with PreviousPage
by using the following code, which uses only a single page and looks for the control on itself. Place a textbox on your Default.aspx page called TextBox1. Then, in the Page_Load
function of the code behind of Default.aspx.cs put this code, then run it in the debugger and step through it.
protected void Page_Load(object sender, EventArgs e)
{
// Following code should find the control, right? Wrong. It's null
var ctrl = Page.FindControl("TextBox1");
// assuming your content placeholder in the masterpage is called MainContent, this works.
var ctrl = Page.Controls[0].FindControl("MainContent").FindControl("TextBox1");
}
So please, don't go saying things like "the PreviousPage
doesn't work as it should if the pages have masterpage", because it's working EXACTLY as it should. The problem is that you don't know how it should be working. Learn how the page object model works.