Sunday, December 27, 2009

How to get or access master page in user control

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.

2 comments:

  1. I'm in .NET 4 and using this method causes a "Circular file references are not allowed." parse error on the control.

    ReplyDelete
  2. Hi Kizmar,
    Can you send me the piece of the code? I want to see why it's happening really. In my code there are no chances of getting the circular reference. Where did you place the code? in user control?

    ReplyDelete