mostlylucid

scott galloway's personal blog...
posts - 916, comments - 758, trackbacks - 11

My Links

News

Archives

Post Categories

Misc. Coding

Dumb little recursive, generic FindControl method...

Doing some app building and I needed to use FindControl to manipulate a control in the OnItemCreated event in a Repeater...well, to save a bit of typing I came up with this extension method:

 

namespace Presentation

{

    public static class ControlHelper

    {

        public static T FindControl<T>(this System.Web.UI.Control root, string controlId, bool recursive) where T: System.Web.UI.Control

        {

            if(root.Controls!=null && root.Controls.Count>0 && root.FindControl(controlId) != null)

            {

                return root.FindControl(controlId) as T;

            }

            else if(recursive)

            {

                return FindControl<T>(root, controlId, recursive);

            }

            return null;

        }

    }

}

 

Pretty simple but it lets me do the following :

       var link = e.Row.FindControl<HyperLink>("MenuLink", true);

        if(link!=null) link.NavigateUrl="http://www.mostlylucid.net";

Not a HUGE time-saver but it just makes my code a bit tidier...

Print | posted on Wednesday, May 14, 2008 11:32 AM | Filed Under [ ASP.NET Code Snippets ]

Feedback

Gravatar

# re: Dumb little recursive, generic FindControl method...

The code you posted will cause a stack overflow because you always pass in root.

2/25/2009 12:44 PM | David Fowler

Comments have been closed on this topic.

Powered by: