如何获取母版页上控件的值?

在运行时,母版页与内容页合并,因此内容页的代码可以访问母版页上的控件。(如果母版页的 ContentPlaceHolder 控

件中包含一些控件,则这些控件被内容页的 Content 控件重写后将不可访问。)这些控件是受保护的,因此不能作为母

版页成员直接访问。但是,可以使用 FindControl 方法定位母版页上的特定控件。如果要访问的控件位于母版页的

ContentPlaceHolder 控件内部,必须首先获取对 ContentPlaceHolder 控件的引用,然后调用其 FindControl 方法获取

对该控件的引用。

下面的示例演示如何获取对母版页上的控件的引用。其中一个被引用的控件位于 ContentPlaceHolder 控件中,另一个则

不是。

// 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;

}

如上所示,可以使用 FindControl 方法访问母版页 ContentPlaceHolder 控件的内容。如果 ContentPlaceHolder 控件

已与 Content 控件的内容合并,ContentPlaceHolder 控件将不会包含自己的默认内容。相反,它将包含在内容页中定义

的文本和控件。

posted on 2011-10-20 10:09  其小本  阅读(1140)  评论(0编辑  收藏  举报