asp.net - 在非母版页中访问母版页控件?

标签 asp.net master-pages

在asp.net中,如何访问非母版页中的母版页控件?

最佳答案

您可以将母版页作为当前页面上的属性进行访问。但是,母版页上的控件受到保护,因此您无法直接访问它们。但您可以使用 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;
}

关于asp.net - 在非母版页中访问母版页控件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9069168/

相关文章:

c# - 如何在 C# 中执行带有参数的命令行参数?

c# - 是否可以在 PostBack C# PCI Compliance 后显示信用卡号

c# - 正则表达式接受部分匹配

asp.net-mvc - 部分 View 继承自主布局

asp.net - 使用 ASP.NET 母版页复制标题标签

asp.net - 在ASP.NET内容页面上设置ScriptManager AsyncPostBackTimeout值

c# - 从长摘要中获取前几个单词(纯字符串或 HTML)

asp.net - System.Web.UI.ViewStateException ,无效的 View 状态

javascript - 从生成的 ID 标记中排除 ContentPlaceHolder

asp.net - 如何从母版页中的代码隐藏动态地将项目添加到项目符号列表