Reputation: 151
How do I access a property defined on my masterpage from codebehind in a usercontrol?
Upvotes: 15
Views: 10498
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
Reputation: 4622
As much as I understood:
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
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
Reputation: 1039498
var master = (this.Page.Master as SiteMaster);
if (master != null)
{
var myProperty = master.MyProperty;
}
Upvotes: 17