You need the reference to the control's NamignContainer if you want to use FindControl. If you don't know (or you don't have a reference to) it you must loop the control-tree recursively:
For example (as extension):
namespace ExtensionMethods
{
public static class ControlExtensions
{
public static Control FindControlRecursive(Control rootControl, string controlID)
{
if (rootControl.ID == controlID) return rootControl;
foreach (Control controlToSearch in rootControl.Controls)
{
Control controlToReturn = FindControlRecursive(controlToSearch, controlID);
if (controlToReturn != null) return controlToReturn;
}
return null;
}
}
}
Use it this way:
using ExtensionMethods;
//.....
Control ctrl = this.FindControlRecursive("myControlID");
But it would be better to use FindControl if you know the NamingContainer because:
- it's faster
- it's more legible
- it's less error-prone: a control's ID just need to be unique inside of it's NamingContainer, hence you might get the wrong control with the recursive method(consider a GridView with it's rows and a Control inside of a TemplateField)
- you learn more how an ASP.NET page works and controls are linked
More informations: MSDN How to: Access Server Controls by ID