Hi,
Here is a nice tips in order to FindControl inside a WebPage, WebControl or any type of Web Components that inherits from System.Web.UI.Control.
Actually we need to do the following boring code ...
protected void Page_Load(object sender, EventArgs e)
{
TextBox txt = null;
Control ctrl = this.FindControl("TextBox1");
if (ctrl != null)
{
txt = (TextBox)ctrl;
}
// OR
TextBox txt2 = this.FindControl("TextBox1") as TextBox;
}
Now we can use the power of Method Extensions to get Strongly Typed Generic Code !
Here is the code
/// <summary>
/// Finds the control.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="control">The Page or Control.</param>
/// <param name="name">The Control Name to Find.</param>
/// <returns></returns>
public static T FindControl<T>(this Control control, String name)
where T : class
{
return control.FindControl(name) as T;
}
Here is some usages
protected void Page_Load(object sender, EventArgs e)
{
TextBox txt = this.FindControl<TextBox>("TextBox1");
}
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType != null && e.Item.ItemType != ListItemType.AlternatingItem)
return;
Button bt = e.Item.FindControl<Button>("Button1");
}
Hope this Help's!
Stay Tuned :)
Views(2527)

