Asp.net
如何訪問嵌套母版頁內的控制項?為什麼它的行為與內容頁面不同?
這兩種情況是否有區別:
(1) 從普通子級訪問母版頁上的屬性
(2) 從嵌套母版頁訪問母版頁上的屬性
我試圖從這樣的內容頁面訪問母版頁中的文本框:
TextBox a; a = (TextBox)Master.FindControl("ayyash"); // Master is declared in MasterType directive defaultTextbox.Text = a.Text; // defaultTextBox is a textbox control inside default.aspx它可以工作,但是當我在嵌套母版頁上應用相同的方法時:
TextBox a; a = (TextBox)Master.FindControl("ayyash"); // Master is declared in MasterType directive myTextBox.Text = a.Text; // myTextBox is a textbox control inside child.master這不起作用,我錯過了什麼嗎?我在regulare page_load處理程序中呼叫這兩個程式碼……
我還注意到我無法從後面的程式碼中設置嵌套母版頁內的文本框值,我肯定缺少一些東西,它是什麼?為了闡明這個問題,這裡有一個例子:
嵌套母版頁:
<%@ Master Language="C#" MasterPageFile="MasterPage.master" AutoEventWireup="false" CodeFile="MasterPage2.master.cs" Inherits="MasterPage2" %> <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"> <asp:textbox id="tx2" runat="server" text="this is two"></asp:textbox> <asp:contentplaceholder id="newstuff" runat="server"></asp:contentplaceholder> </asp:Content>後面的程式碼:
Response.Wrote(tx2.Text);我什麼都沒有,為什麼我錯過了什麼?請注意,我還嘗試了遞歸查找控制項:
String str = ((TextBox)((Content)FindControl("Content2")).FindControl("tx2")).Text;依然沒有
我在這裡讀了幾件事: http ://www.odetocode.com/Articles/450.aspx 發現中間的嵌套頁面從不呼叫 Page_Load!相反,它會觸發一個載入事件,您可以擷取該事件以設置任何欄位,因此答案是:在嵌套頁面上執行以下操作:
protected override void OnLoad(EventArgs e) { myTextBox.Text = "anything"; base.OnLoad(e); }
ContentPlaceHolder cp = (ContentPlaceHolder)this.Master.Master.FindControl("ContentPlaceHolder1"); //base content place holder id Label objLabel3 = (Label)cp.FindControl("lblNested"); //lblNested is id in nested master page