Find A Control Recursively

This is a helper that can find a control recursively based on an ID.

/// <summary>
/// This will find a control with the given ID if it exists.
/// </summary>
/// <param name="targetRoot">This is the place to start searching.</param>
/// <param name="targetId">This is the ID to find.</param>
/// <returns>This is the control if the ID is found, otherwise it is null.</returns>
/// <remarks>
/// Thanks for this code goes to the following...
/// http://west-wind.com/Weblog/posts/5127.aspx 
/// </remarks>
public static Control FindControlRecursive(Control targetRoot, string targetId)
{
	targetId = (targetId + "").Trim();

	if (targetRoot == null)
	{
		//Hardjump.
		return null;
	}

	if (targetRoot.ID == targetId)
	{
		//Hardjump.
		return targetRoot;
	}

	if (targetRoot.Controls != null)
	{
		foreach (Control myControlTemp in targetRoot.Controls)
		{
			//Recursion.
			Control myControlFound = PageHelper.FindControlRecursive(myControlTemp, targetId);

			if (myControlFound != null)
			{
				//Hardjump.
				return myControlFound;
			}
		}
	}

	return null;
}

HTH.

Thank you.

— Mark Kamoski

Advertisements

Author: mkamoski1

n/a