Sunday, February 05, 2023

A Better Control.FindControl for WebForms

I don't do much with ASP.Net WebForms anymore. In truth, I don't know anyone who does.

But there's still plenty of WebForms code out there, and from time to time it needs maintenance.  

I had occasion the other day to create a helper extension method for working with individual controls within templated list controls (like DataGrid, DataList, and Repeater.)

If you've ever done it, you know why this was needed.

        /// <summary>
        /// Find a <see cref="Control"/> with the id <paramref name="controlId"/> within <paramref name="namingContainer"/> and cast it to
        /// the type <typeparamref name="TControl"/>. If the control cannot be found, or cannot be cast to <typeparamref name="TControl"/>,
        /// <c>null</c> will be returned.
        /// </summary>
        /// <typeparam name="TControl"></typeparam>
        /// <param name="namingContainer"></param>
        /// <param name="controlId"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        public static TControl FindControl<TControl>(this Control namingContainer, string controlId) where TControl : Control {

            if (namingContainer == null) {
                throw new ArgumentNullException(nameof(namingContainer));

            return namingContainer.FindControl(controlId) as TControl;