Return to Snippet

Revision: 36312
at November 20, 2010 09:54 by housecor


Updated Code
public static class Extensions
	{
		/// <summary>
		/// Searches recursively in this control to find a control with the name specified.
		/// </summary>
		/// <param name="root">The Control in which to begin searching.</param>
		/// <param name="id">The ID of the control to be found.</param>
		/// <returns>The control if it is found or null if it is not.</returns>
		public static Control FindControlR(this Control root, string id)
		{
			System.Web.UI.Control controlFound;
			if (root != null)
			{
				controlFound = root.FindControl(id);
				if (controlFound != null)
				{
					return controlFound;
				}

				foreach (Control c in root.Controls)
				{
					controlFound = c.FindControlR(id);

					if (controlFound != null)
					{
						return controlFound;
					}
				}
			}

			return null;
		}
	}

Revision: 36311
at November 20, 2010 09:53 by housecor


Initial Code
public static class Extensions

{

    /// <summary>

    /// Searches recursively in this control to find a control with the name specified.

    /// </summary>

    /// <param name="root">The Control in which to begin searching.</param>

    /// <param name="id">The ID of the control to be found.</param>

    /// <returns>The control if it is found or null if it is not.</returns>

    public static Control FindControlR(this Control root, string id)

    {

        System.Web.UI.Control controlFound; 

        if (root != null) 

        { 

            controlFound = root.FindControl(id);

            if (controlFound != null)

            {

                return controlFound;

            }

            foreach (Control c in root.Controls) 

            {

                controlFound = c.FindControlR(id);

                if (controlFound != null)

                {

                    return controlFound;

                }

            } 

        } 

        return null;

    }

}

Initial URL
http://aspadvice.com/blogs/name/archive/2008/03/31/Creating-a-Recursive-FindControl-Extension-Method.aspx

Initial Description
And usage:

protected void Page_Load(object sender, EventArgs e)

{

    Label theLabel = form1.FindControlR("ControlToFind") as Label;

    if (theLabel != null)

    {

        theLabel.Text = "Found it!";

    }

}

Initial Title
Find control recursively via extension method

Initial Tags

                                

Initial Language
C#