I have the following situation:
Page1.aspx is based on a master page and has a hidden field called “hdFlotaID” in it. On the same page I have a button for which I set PostBackUrl="Page2.aspx". When I click the buton, the Page2 is loaded but I can’t get the hidden field. I tried both (as I saw on msdn or other posts):
this.PreviousPage.Controls[0].FindControl("hdFlotaID")
and
this.PreviousPage.FindControl("hdFlotaID")
but they return null.
This.PreviousPage returns a value, but Controls[0] of that value seems to return the masterpage and I want the content page.
I also checked and the hidden field has runat server value and ClientID mode is set to static (I even checked the generated HTML and the ID is correct)
Can you please help me! Thank you
SOLUTION: Ok,so based on your help I got it to work like this
this.PreviousPage.Controls[0].FindControl("CPH").FindControl("hdFlotaID")
where CPH is the ID of the ContentPlaceHolder from the master page.
Also the ideea with the public property is very good allthough in my case adding the PreviousPageType directive was giving me some errors about namespaces. If I removed the directive and cast it in codebehind it works fine.
Thank you all very much
FindControl searches only one level i.e. top level container and all the controls of your content page are not directly in Master control collection rather inside master’s content control collection.
To achieve this
1) you need to write a recursive version of FindControl. try like this (did not tested it):
or
2) Typecast the previous page to the type of page it is. Then you can access controls.