c# - ASP.NET - 嵌套母版页中的 FindControl

标签 c# asp.net vb.net master-pages

如何方便地访问嵌套母版页中的控件?


访问母版页控件通常很简单:

Dim ddl As DropDownList = Master.FindControl("ddl")

但是,当我的设置如下时,找不到控件,可能是因为控件位于 content block 内:

1 根大师

<asp:ContentPlaceHolder ID="cphMainContent" runat="server" />

2 嵌套主控

<%@ Master Language="VB" MasterPageFile="~/Root.master" AutoEventWireup="false" CodeFile="Nested.master.vb" Inherits="Nested" %>

<asp:Content ID="MainContent" ContentPlaceHolderID="cphMainContent" runat="server">
  <asp:DropDownList ID="ddl" runat="server" DataTextField="Text" DataValueField="ID"/>
</asp:Content>

3 内容页面 VB.NET

Dim ddl As DropDownList = Master.FindControl("ddl")

解决方法

我通过向上遍历树找到根内容占位符 cphMainContent 然后在其中寻找控件找到了解决方案。

cphMainContent = CType(Master.Master.FindControl("cphMainContent"), ContentPlaceHolder)
Dim ddl As DropDownList = cphMainContent .FindControl("ddl")

然而,这个解决方案似乎非常迂回且效率低下。

能否直接从母版页的 content block 中访问该控件?

最佳答案

这是一个可以处理任意数量的嵌套级别的扩展方法:

public static class PageExtensions
{
    /// <summary>
    /// Recursively searches this MasterPage and its parents until it either finds a control with the given ID or
    /// runs out of parent masters to search.
    /// </summary>
    /// <param name="master">The first master to search.</param>
    /// <param name="id">The ID of the control to find.</param>
    /// <returns>The first control discovered with the given ID in a MasterPage or null if it's not found.</returns>
    public static Control FindInMasters(this MasterPage master, string id)
    {
        if (master == null)
        {
            // We've reached the end of the nested MasterPages.
            return null;
        }
        else
        {
            Control control = master.FindControl(id);

            if (control != null)
            {
                // Found it!
                return control;
            }
            else
            {
                // Search further.
                return master.Master.FindInMasters(id);
            }
        }
    }
}

像这样使用任何继承自 System.Web.UI.Page 的类的扩展方法:

DropDownList ddl = (DropDownList)Page.Master.FindInMasters("ddl");
if (ddl != null)
{
    // do things
}

关于c# - ASP.NET - 嵌套母版页中的 FindControl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41037854/

相关文章:

c# - 摆脱临时文件夹中的 Crystal Report 生成的文件 - Visual Studio 2008

c# - 在启动 Appium session 之前获取可用设备列表

c# - "Object doesn' t 在IE8和IE7中支持这个属性或方法

asp.net - SQL Server 和 IIS 如何处理断开的连接?

javascript - 如果禁用 javascript,则使用服务器端代码

arrays - Visual Basic 数组 case 语句

VB.NET - 对计算机上的所有屏幕进行截图

c# - 使用 COM 在 C++ 中实例化 C# 类成员

C#控制台应用程序,退出缓慢

c# - 来自 textBox 的值没有被插入到数据库中