今天遇到这样一个问题, 在模板页中放置的一个服务器控件,竟然在调用引用该模板页的page中找不到。

具体情况如下

在模板页中有一控件:

<asp:HyperLink ID="hylkShowFollowers" runat="server" Text="列表链接"></asp:HyperLink>

 有一个page,引用了这个模板页,在page_load中通过调用Master.FindControl("hylkShowFollowers"), 返回为空。

 查了一些资料之后,引起这个问题的原因是由于引用了masterpage之后呢,控件的布局发生了改变。需要通过递归调用

才能找到该控件。

代码如下:

     /// <summary>
        /// Finds a Control recursively. Note finds the first match and exists
        /// </summary>
        /// <param name="ContainerCtl"></param>
        /// <param name="IdToFind"></param>
        /// <returns></returns>
        public static Control FindControlRecursive(Control Root, string Id)
        {
            if (Root.ID == Id)
            {
                return Root;
            }

            foreach (Control Ctl in Root.Controls)
            {
                Control FoundCtl = FindControlRecursive(Ctl, Id);

                if (FoundCtl != null)

                    return FoundCtl;
            }
            return null;
        }

 

调用方法:

      var hylkShowFollowers = FindControlRecursive(Master, "hylkShowFollowers") as Hyperlink;

      if(hylkShowFollowers != null)  

      {   //加入自己的代码}

 

改进版,支持MasterPage扩展方法:

/// <summary>
        /// Finds a Control recursively. Note finds the first match and exists
        /// </summary>
        /// <param name="ContainerCtl"></param>
        /// <param name="IdToFind"></param>
        /// <returns></returns>
        public static Control FindControlRecursive(this MasterPage Root, string Id)
        {
            if (Root.ID == Id)
            {
                return Root;
            }

            foreach (Control Ctl in Root.Controls)
            {
                Control FoundCtl = FindControlRecursive(Ctl, Id);

                if (FoundCtl != null)

                    return FoundCtl;
            }

            return null;

        } 

 

参考:

    http://www.west-wind.com/Weblog/posts/5127.aspx

 

EOF

 

posted on 2010-11-17 10:21  蔡春升  阅读(282)  评论(0编辑  收藏  举报