1

Is there a way to instantiate and use a usercontrol (.ascx) if given you have its Type (ie. typeof(MyUserControl))?

With regular asp.net controls like a textbox or a dropdownlist you can just make a new instance and add it to a controls collection. This doesnt appear to work for User controls. While you can make a new instance and add it to a collection, and have all of its events fire, it will not actually render to the page. Typically you would call Page.LoadControl() with the path to the .ascx

This presents a problem if all you have is its type. How can you get the path to the .ascx to give to the LoadControl method. Ideally I would also like to not have to have a reference to the Page object

Oleks
  • 31,955
  • 11
  • 77
  • 132
Mr Bell
  • 9,228
  • 18
  • 84
  • 134

3 Answers3

3

No. This is not possible; the ASCX virtual path must be supplied to dynamically load a User Control with markup and there is no internal mapping of types of virtual paths.

However, because I am still lazy, here is the approach I used that is still "type safe", and isolates the resolving issue to a single location in code. It still requires access to the "Page object", but otherwise takes care of the silly details.

Here is the brief explanation:

  1. Use the type to look-up the relative (to my root) ASCX path using a heuristic to map types from namespace to virtual path; allow a way to specify a manual mapping, and use that if specified
  2. Turn the relative path of the type into the correct/full virtual path
  3. Load the control with the virtual path
  4. Continue as though nothing has happened

Enjoy (I just copy'n'pasted select parts from my project, YMMV):

    /// <summary>
    /// Load the control with the given type.
    /// </summary>
    public object LoadControl(Type t, Page page)
    {
        try
        {
            // The definition for the resolver is in the next code bit
            var partialPath = resolver.ResolvePartialPath(t);
            var fullPath = ResolvePartialControlPath(partialPath);
            // Now we have the Control loaded from the Virtual Path. Easy.
            return page.LoadControl(fullPath);
        } catch (Exception ex)
        {
            throw new Exception("Control mapping failed", ex);
        }
    }

    /// <summary>
    /// Loads a control by a particular type.
    /// (Strong-typed wrapper for the previous method).
    /// </summary>
    public T LoadControl<T>(Page page) where T : Control
    {
        try
        {
            return (T)LoadControl(typeof (T), page);
        } catch (Exception ex)
        {
            throw new Exception(string.Format(
                "Failed to load control for type: {0}",
                typeof (T).Name), ex);
        }
    }

    /// <summary>
    /// Given a partial control path, return the full (relative to root) control path.
    /// </summary>
    string ResolvePartialControlPath(string partialPath)
    {
        return string.Format("{0}{1}.ascx",
            ControlPathRoot, partialPath);
    }

The code listing for ControlResolver:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FooBar
{
    class ControlResolver
    {
        const string BaseNamespace = "TheBaseControlNameSpace";

        readonly IDictionary<Type, string> resolvedPaths = new Dictionary<Type, string>();

        /// <summary>
        /// Maps types to partial paths for controls.
        /// 
        /// This is required for Types which are NOT automatically resolveable
        /// by the simple reflection mapping.
        /// </summary>
        static readonly IDictionary<Type, string> MappedPartialPaths = new Dictionary<Type, string>
        {
            { typeof(MyOddType), "Relative/ControlPath" }, // No virtual ~BASE, no .ASXC
        };

        /// <summary>
        /// Given a type, return the partial path to the ASCX.
        /// 
        /// This path is the path UNDER the Control Template root
        /// WITHOUT the ASCX extension.
        /// 
        /// This is required because there is no mapping maintained between the class
        /// and the code-behind path.
        /// 
        /// Does not return null.
        /// </summary>
        public string ResolvePartialPath (Type type)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            string partialPath;
            if (resolvedPaths.TryGetValue(type, out partialPath))
            {
                return partialPath;
            } else
            {
                string mappedPath;
                if (MappedPartialPaths.TryGetValue(type, out mappedPath))
                {
                    resolvedPaths[type] = mappedPath;
                    return mappedPath;
                } else
                {
                    // Since I use well-mapped virtual directory names to namespaces,
                    // this gets around needing to manually specify all the types above.
                    if (!type.FullName.StartsWith(BaseNamespace))
                    {
                        throw new InvalidOperationException("Invalid control type");
                    } else
                    {
                        var reflectionPath = type.FullName
                            .Replace(BaseNamespace, "")
                            .Replace('.', '/');
                        resolvedPaths[type] = reflectionPath;
                        return reflectionPath;
                    }
                }
            }
        }
    }
}
0
  ' Load the control 
  Dim myUC as UserControl = LoadControl("ucHeading.ascx") 

  ' Set the Usercontrol Type 
  Dim ucType as Type = myUC.GetType() 

  ' Get access to the property 
  Dim ucPageHeadingProperty as PropertyInfo = ucType.GetProperty("PageHeading") 

  ' Set the property 
  ucPageHeadingProperty.SetValue(myUC,"Access a Usercontrol from Code Behind",Nothing) 

  pnlHeading.Controls.Add ( myUC ) 
Adam
  • 1
-1

You may be out of luck here.

This fellow was not able to get help doing this.

And they told this person it can't be done.

Community
  • 1
  • 1
DOK
  • 32,337
  • 7
  • 60
  • 92