开发者

Accessing masterpage property from a usercontrol

开发者 https://www.devze.com 2023-03-14 06:16 出处:网络
How do I access a开发者_运维问答 property defined on my masterpage from codebehind in a usercontrol?var master = (this.Page.Master as SiteMaster);

How do I access a开发者_运维问答 property defined on my masterpage from codebehind in a usercontrol?


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


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


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;


this.NamingContainer.Page.Master.Property;   


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"


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>

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号