原文地址:http://msdn2.microsoft.com/zh-cn/library/xxwa0ff0(VS.80).aspxASP.NET 如何:引用 ASP.NET 主版頁面的內容
可以在內容頁中編寫代碼來引用主版頁面中的屬性、方法和控制項,但這種引用有一定的限制。對於屬性和方法的規則是:如果它們在主版頁面上被聲明為公用成員,則可以引用它們。這包括公用屬性和公用方法。在引用主版頁面上的控制項時,沒有只能引用公用成員的這種限制。
引用主版頁面上的公用成員
在內容頁中添加 @ MasterType 指令。在該指令中,將 VirtualPath 屬性設定為主版頁面的位置,如下面的樣本所示:
<%@ MasterType virtualpath="~/Masters/Master1.master" %>
此指令使內容頁的 Master 屬性被強型別化。
編寫代碼,將主版頁面的公用成員用作 Master 屬性的一個成員,如本例中,將主版頁面名為 CompanyName 的公用屬性的值賦給內容頁上的一個文字框:
引用主版頁面上的控制項
使用 FindControl 方法,將 Master 屬性的傳回值用作命名容器。
下面的程式碼範例示範如何使用 FindControl 方法擷取對主版頁面上的兩個控制項的引用(一個 TextBox 控制項和一個 Label 控制項)。因為 TextBox 控制項處在 ContentPlaceHolder 控制項的內部,必須首先擷取對 ContentPlaceHolder 的引用,然後使用其 FindControl 方法來定位 TextBox 控制項。
Visual Basic 複製代碼Sub Page_Load() Dim mpContentPlaceHolder As ContentPlaceHolder Dim mpTextBox As TextBox mpContentPlaceHolder = _ CType(Master.FindControl("ContentPlaceHolder1"), _ ContentPlaceHolder) If Not mpContentPlaceHolder Is Nothing Then mpTextBox = CType(mpContentPlaceHolder. _ FindControl("TextBox1"), TextBox) If Not mpTextBox Is Nothing Then mpTextBox.Text = "TextBox found!" End If End If ' Gets a reference to a Label control not in a ' ContentPlaceHolder Dim mpLabel As Label mpLabel = CType(Master.FindControl("masterPageLabel"), Label) If Not mpLabel Is Nothing Then Label1.Text = "Master page label = " + mpLabel.Text End If End Sub
C# 複製代碼void Page_Load() { // 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 not in // a ContentPlaceHolder Label mpLabel = (Label) Master.FindControl("masterPageLabel"); if(mpLabel != null) { Label1.Text = "Master page label = " + mpLabel.Text; } }
請參見概念
ASP.NET 主版頁面概述
以編程方式使用 ASP.NET 主版頁面
其他資源
以編程方式訪問 ASP.NET 控制項