2011-02-12 92 views
13

它很容易從內容頁訪問母版頁控制就像從母版頁的內容頁面的如何從母版頁訪問asp.net

protected void Page_Load(object sender, EventArgs e) 
{ 
    // content page load event 
    DropDownList thisDropDown = this.Master.FindControl("someDropDown") as DropDownList; 
    userLabel.Text = thisDropDown.SelectedValue; 
} 

,但我怎麼能訪問控制內容的頁面控件。假設內容頁面中有一個文本框,並且在母版頁中有一個按鈕。我想,當我點擊母版頁按鈕,然後我想在母版頁的標籤內容頁面中顯示文本框的文本。如何實現它。請使用代碼示例幫助我。謝謝。

回答

32

在母版頁按鈕單擊事件應該由訪問頁面內容: -

protected void Button1_Click(object sender, EventArgs e) 
{ 
    TextBox TextBox1 = (TextBox)ContentPlaceHolder1.FindControl("TextBox1"); 
    if (TextBox1 != null) 
    { 
     Label1.Text = TextBox1.Text; 
    } 
} 
+1

+1爲徹底。 ;-) – 2011-02-12 18:45:23

+0

再次+1爲徹底。 ;-) – Monodeep 2012-09-28 21:06:57

+1

太愚蠢了,這麼多的代碼是必需的......我不是歸因於你的答案,而是歸功於ASP.net模型 – user3308043 2014-06-03 23:36:15

3

它已經有一段時間,但我相信你可以使用的ContentPlaceHolder作爲參考這樣做:

Control control = this.myContentPlaceHolder.FindControl("ContentPageControlID"); 
3

在我看來,使用Master頁面的事件提升更好,例如,可以在競爭網頁中捕獲此事件以更改此頁面上的某個競爭對手。主要優點是可重用性。將來,您可能需要更改Master頁面上其他內容頁面上的內容,在這種情況下,您應該只將事件處理程序添加到此內容頁面,而不更改母版頁上的代碼。在這種方法中,您不需要從某個內容頁面硬編碼控件名稱。此外,您不應該爲某些內容的控制添加依賴項。

例如,您可以找到一個實現示例here

1

你應該尋找的ContentPlaceHolder從母版頁隨後的ContentPlaceHolder在母版頁的孩子

this.Page.Master.FindControl("ContentPlaceHolder1").FindControl("controlAFromPage"); 
0

您可以使用此找到控制:

ContentPlaceHolder contentPage = Page.MasterPage.FindControl("ContentPlaceHolder1") as ContentPlaceHolder; 
Label lblHead =(Label)contentPage.FindControl("lblHeading"); 
Response.Write(lblHead.Text); 

來源: http://xpode.com/ShowArticle.aspx?ArticleId=629

-1

試試這個代碼

Page.Master.FindControl("MainContent").FindControl("DivContainer_MyProfile").Visible = True