Skip to content

Instantly share code, notes, and snippets.

@richardkundl
Created February 13, 2013 21:13
Show Gist options
  • Save richardkundl/4948340 to your computer and use it in GitHub Desktop.
Save richardkundl/4948340 to your computer and use it in GitHub Desktop.
Find custom controls in aspx page any depth
/// <summary>
/// Extension method for the "Page" class
/// </summary>
public static class PageHelper
{
/// <summary>
/// Find control in the page
/// </summary>
/// <typeparam name="T">return control type(eg. TextBox)</typeparam>
/// <param name="page">Actual Page</param>
/// <param name="id">control id</param>
/// <returns></returns>
public static T GetControl<T>(this Page page, string id)
where T : Control
{
return (FindControlRecursive(page, id) as T);
}
/// <summary>
/// Find control recursive
/// </summary>
/// <param name="root">root contol(eg. Page)</param>
/// <param name="id">control id</param>
/// <returns></returns>
private static Control FindControlRecursive(Control root, string id)
{
if (root.ID == id)
{
return root;
}
foreach (Control ctl in root.Controls)
{
var foundCtl = FindControlRecursive(ctl, id);
if (foundCtl != null)
{
return foundCtl;
}
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment