Thursday, March 15, 2007

ASP.NET Find Control Recursively

Sometimes we need to get a control instance inside a page. Looking up each control recursively is the easiest way:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
LoginInfoUserControl loginControl = FindControl<LoginInfoUserControl>(this.Page, "ucLogin");
}

public static T FindControl<T>(Control root, string controlID) where T : class
{
if (root is T && root.ID == controlID)
{
return root as T;
}
foreach (Control control in root.Controls)
{
T foundControl = FindControl<T>(control, controlID);
if (foundControl != null)
{
return foundControl;
}
}
return null;
}
}