Find A LinkButton Recursively By Text

If one needs to find a dynamically-generated LinkButton, for example, and if one does not know the ID of the LinkButton, then one may use something like the following…

/// <summary>
/// This will return the 1st LinkButton found that has the given text, searching deep into all contained controls.
/// </summary>
/// <param name="targetRoot">This is the starting control.</param>
/// <param name="targetTextToFind">This is the text to find, not-case-sensitive.</param>
/// <returns>This is the control found or null if the control is not found.</returns>
public static LinkButton FindLinkButtonRecursiveByText(Control targetRoot, string targetTextToFind)
{
	targetTextToFind = (targetTextToFind + "").Trim().ToLower();

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

	if ((targetRoot.GetType() == typeof(System.Web.UI.WebControls.LinkButton)) ||
		(targetRoot.GetType().ToString().Trim().ToLower() == PageHelper.DefaultTypeNameForDataControlLinkButton.Trim().ToLower()))
	{
		LinkButton myLinkButton = (LinkButton)targetRoot;
		string myLinkButtonText = myLinkButton.Text.Trim().ToLower();
		Debug.WriteLine("myLinkButtonText='" + myLinkButtonText + "'");

		if (myLinkButtonText == targetTextToFind)
		{
			return (LinkButton)targetRoot;
		}
	}

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

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

	return null;
}

HTH.

Thank you.

— Mark Kamoski

Advertisements

Author: mkamoski1

n/a