Johan
Johan

Reputation: 151

Accessing masterpage property from a usercontrol

How do I access a property defined on my masterpage from codebehind in a usercontrol?

Upvotes: 15

Views: 10498

Answers (6)

ni3.net
ni3.net

Reputation: 387

In Case of your Master Page is fixed than You can find control and property like this:

    MasterPageName mp =(MasterPageName) Page.Master;
   //find a control
    Response.Write((mp.FindControl("txtmaster") as TextBox).Text);
   //find a property
   Response.Write(mp.MyProperty.Text);

//on MasterPageName.cs

 public TextBox MyProperty
 {
    get { return txtmaster; }
 }

//on MasterPageName.Master

<asp:TextBox runat="server" ID="txtmaster"></asp:TextBox>

Upvotes: -1

Simple Fellow
Simple Fellow

Reputation: 4622

As much as I understood:

  1. there is a Master Page (MasterPage.master)
  2. a web page (Default.aspx) which is using MasterPage.
  3. the webpage has a user control.
  4. Now you want to access a property of a MasterPage from this user control.

Lets say in the MasterPage there is a property called name like

public string Name{ get{return "ABC";} }

Now you want to access this property from the UserControl.

For this purpose you'll first have to register the master page in the user control like this.

<%@ Register TagPrefix="mp" TagName="MyMP" Src="~/MasterPage.master" %>

Now you'll first have to get the reference of the page this user control is residing in and then get the Master Page of that page. The code will be like this.

System.Web.UI.Page page = (System.Web.UI.Page)this.Page;
MasterPage1 mp1 = (MasterPage1)page.Master;

lbl1.Text= mp1.Name;

Upvotes: 3

Nazmul
Nazmul

Reputation: 7218

If the MasterPage is like this,

public partial class MasterPage : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //
    }

    // the property which I would like to access from user control  
    public String MyName
    {
        get
        {
            return "Nazmul";
        }
    }  
}

Then from the user control, you can access "MyName" by this way,

MasterPage m = Page.Master as MasterPage;
Type t = m.GetType();

System.Reflection.PropertyInfo pi = t.GetProperty("MyName");

Response.Write( pi.GetValue(m,null)); //return "Nazmul"

Upvotes: 0

The Evil Greebo
The Evil Greebo

Reputation: 7138

Page.Master exposes the underlying master page, if any.

Upvotes: 6

Saurabh
Saurabh

Reputation: 5727

this.NamingContainer.Page.Master.Property;   

Upvotes: 2

Darin Dimitrov
Darin Dimitrov

Reputation: 1039498

var master = (this.Page.Master as SiteMaster);
if (master != null)
{
    var myProperty = master.MyProperty;
}

Upvotes: 17

Related Questions