how to access master page control from content page
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I have a master page which contains a label for status messages. I need to set the status text from different .aspx pages. How can this be done from the content page?
public partial class Site : System.Web.UI.MasterPage { public string StatusNachricht { get { return lblStatus.Text; } set { lblStatus.Text = value; } } protected void Page_Load(object sender, EventArgs e) { } }
I have tried this, but was unsuccessful in making it work:
回答1:
In the MasterPage.cs file add the property of Label like this:
public string ErrorMessage { get { return lblMessage.Text; } set { lblMessage.Text = value; } }
On your aspx page, just below the Page Directive add this:
// Add this
And in your codebehind(aspx.cs) page you can then easily access the Label Property and set its text as required. Like this:
Because you cannot use this in a field and Master as Site is the same as this.Master as Site. So just initialize the field from Page_Init when the page is fully initialized and you can use this:
Site master = null; protected void Page_Init(object sender, EventArgs e) { master = this.Master as Site; }
回答5:
I have a helper method for this in my System.Web.UI.Page class
protected T FindControlFromMaster(string name) where T : Control { MasterPage master = this.Master; while (master != null) { T control = master.FindControl(name) as T; if (control != null) return control; master = master.Master; } return null; }
then you can access using below code.
Label lblStatus = FindControlFromMaster
回答6:
This is more complicated if you have a nested MasterPage. You need to first find the content control that contains the nested MasterPage, and then find the control on your nested MasterPage from that.