2012-01-30 78 views

回答

5

您可以访问母版页作为您当前页面上的一个属性。但是,母版页上的控件受到保护,因此您无法直接访问它们。但是您可以使用FindControl(string name)访问它们。您需要使用的代码取决于控件位于内容占位符之内还是之外。

// 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; 
} 
+0

谁是'Label1'? – 2016-04-06 12:47:17

2

在网页中添加此访问母版页的内容Master Page : programatically access

<%@ MasterType virtualpath="Your MasterPath" %> 

你可以做这样的(另一种方式)

MasterPage mstr 
Label lbl 
mstr = Page.Master 
If (mstr.ID == "yourMasterIDString") 
{ 
    lbl = mstr.FindControl("lblBar") 
     If (lbl !=null) 
      { 
       lbl.Text = "Do some Logic" 
      } 
} 
2

的使用可以

TextBox txt1 = (TextBox)this.Master.FindControl("MytxtBox"); 
txt1.Text="Content Changed from content page"; 
相关问题