2012-01-30 64 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"; 
相關問題