ASP .NET 2.0 Accessing Parent Pages from User Controls
I recently ran into a problem when I was trying to access properties in a parent page from a user control.
If I have my parent page, MyPage.aspx under the root folder, and my user control, MyControl.ascx in a sub-folder called Controls, in ASP .NET 1.x, the following was possible.
public partial class MyPage
{
private string myString;
public string MyString
{
get { return myString; }
}
void Page_Load(object sender, EventArgs e)
{
myString = “my string”;
}
}
public partial class Controls_MyControl
{
protected void Page_Load(object sender, EventArgs e)
{
string myString = ((MyPage)this.Page).MyString;
}
}
This way of accessing the properties in the parent’s page worked just fine. But if you try to build this project, you will get a compilation error saying MyPage could not be found in the assembly.
This is no longer possible because of the nature of the .NET 2.0 compiler. Partial classes will be compiled at run time, and each sub directory will be placed into different assemblies. This is why MyPage in my example was not visible to MyControl, which resides in a different directory.
In order to work around this problem, you’d have to utilize the App_Code folder so that your parent page will inherit from a base page, and the base page will contain the properties. This way, you can cast your parent page into the PageBase. in your user control to access the properties.
public partial class Controls_MyControl
{
protected void Page_Load(object sender, EventArgs e)
{
string myString = ((PageBase)this.Page).MyString;
}
}
I had a similar problem with dynamically loaded user controls when I tried to cast them back to their own class because those user controls were in a different directory. In this case, I’ve seen a workaround that requires the <% Register > tag for the dynamically loaded user controls on the page.
I wonder if there’s a better workaround, or the right way to get around this problem,