Referencing the Page from a User Control
An Advanced technique I like to do in a User Control (.ascx file) is reference the parent page to get properties. Some common examples might be setting the page title, meta tags or other 'expected' controls on the page based on the data or status of the user control. I learned to really leverage this technique back in my DotNetNuke days to set the page title based on a product, etc.
I have discovered in ASP.NET 2.0 this can be a problem because the page class in not really available to other objects in the application. In this example I will show you a common property I might declare in the Usercontrol class to reference the parent page:
Protected ReadOnly Property ParentPage() As MyParentPage
Return CType(Page, MyParentPage)
The problem you will find is MyParent has been tagged by the IDE as non-existant. I am not totally sure why this is the case, but I think it has to do with partial pages in ASP.NET 2.0. If you take a look in the Class Viewer you will not find the page class either, which tells me it really does not exist for us to reference. Now I am going to bet there is an easy way to reference it that just has not been spoken about in the community at this point, but I found a solution.
One of the key advantages Visual Studio 2005 has over 2003 is it really lets you create your own base classes, which I have already mentioned several times in my Blog this year. Since I create a common base class and start deriving from there I thought I would leverage that, and it worked.
Create a base page class to inherit your parent page, or the page that will contain the user control. It should inherit from the System.Web.UI.Page somewhere in it's path. It should contain any methods, properties or objects that you want any user control to reference as well as your actual page.
#Region " Private Properties "
protected Property MyCustomDataId() As Integer
'Return Your data Here
Set(ByVal Value As Integer)
'Set Your data Here = Value
Protected dc As MyCustomdataController
Protected di As MyCustomDataInfo
The actual page that is referenced by your page can be this page or (this is easier IMHO) the class in your page-behind. The UserControl will reference the base page and everything should work out fine. Make sure any delarations are either protected or public so your page and user control can access them.
I hate you have to go through some extra hoops to accomplish this, but I guess it is just one of the pains we have to endure to all the advantages of ASP.NET 2.0.