My requirement is I want to get the reference to the master page and access the public property of a master page in user control. As we know that master page is also inherited from the user control, I can say this is simple and we can easily get the reference.
I am using master page in my web application and all pages are using that master page. And there are user controls in the application and my requirement is how to access the master page property inside a user control. Below is the solution how I resolved the problem.
In user control ASCX file declare the below line to establish the reference to the master page.
<%@ Reference Control="~/DefaultMaster.Master" %>
IN the ASCX.CS file, we need to fill the master page object to access it's properties. For this,
- Declare a master page class variable as the user control class variable as shown below.
DefaultMaster masterpage = null;
NOTE: Remember the DefaultMaster is the class of DefaultMaster.master class.
- In Page_Load event of user control, fill the masterpage object as shown.
masterpage = this.Page.Master as DefaultMaster;
Now, you are all set to use master page object and access everything inside it. If you observed, everything is simple object model. I am just accessing the objects. I think, you got better idea and the way I used. Hope this helps and any comments always welcome.