在asp.net中,如何在非母版页中访问母版页控件?
You can access the Masterpage as a property on your current page. However, the controls on your master page are protected so you can't access them directly. But you can access them by using FindControl(string name)
. The code you need to use depends on if the control is inside or outside a content place holder.
// Gets a reference to a TextBox control inside a ContentPlaceHolder
ContentPlaceHolder mpContentPlaceHolder;
TextBox mpTextBox;
mpContentPlaceHolder =
(ContentPlaceHolder)Master.FindControl("ContentPlaceHolder1");
if(mpContentPlaceHolder != null)
{
mpTextBox = (TextBox) mpContentPlaceHolder.FindControl("TextBox1");
if(mpTextBox != null)
{
mpTextBox.Text = "TextBox found!";
}
}
// Gets a reference to a Label control that is not in a
// ContentPlaceHolder control
Label mpLabel = (Label) Master.FindControl("masterPageLabel");
if(mpLabel != null)
{
Label1.Text = "Master page label = " + mpLabel.Text;
}
add this in your webPage to access the contents of master page Master Page : programatically access
<%@ MasterType virtualpath="Your MasterPath" %>
you can do like this (alternative way )
MasterPage mstr
Label lbl
mstr = Page.Master
If (mstr.ID == "yourMasterIDString")
{
lbl = mstr.FindControl("lblBar")
If (lbl !=null)
{
lbl.Text = "Do some Logic"
}
}
Use can
TextBox txt1 = (TextBox)this.Master.FindControl("MytxtBox");
txt1.Text="Content Changed from content page";
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.