Control.TryFindControl Extension Method

Following on from my last post creating an extension method to use FindControl recursively I thought it would be cool to also have a TryFindControl method which works in a similar way to Int32.TryParse which I use regularly.

Below is a generic extension method that uses my previously created recursive FindControl method to cast the object to the correct type if found and send it back as an out parameter, then return a boolean indicating if the control was found.

public static bool TryFindControl<T>(this Control ctrl, string id, out T control, bool recursive) where T : class
{
    Control ctrlFound = ctrl.FindControl(id, recursive);
    control = ctrlFound as T;
    return ctrlFound is T;
}

The method could then be used like so.

TextBox txt = null;
if (this.TryFindControl<TextBox>("txtName", out txt, true))
{
    txt.Text = "Joe Stevens";
}
Posted on by Joe in ASP.NET, C#

Add a Comment