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 @ Wednesday, May 14, 2008 11:32 AM

Comments on this entry:

No comments posted yet.

Your comment:

Title:
Name:
Email:
Website:
 
Italic Underline Blockquote Hyperlink
 
 
Please add 1 and 4 and type the answer here: