Wednesday, September 23, 2009

Dynamically Loading .NET Custom Controls Using Reflection

The usual way of adding custom controls on a Web Forms page is by specifying the required HTML markup in the Web Page. But in real world applications we may need to dynamically load custom controls. Here is one way of doing so using Reflections.


System.Reflection.Assembly a =
System.Reflection.Assembly.Load("Myproject.Controls");
Type t = a.GetType(string.Concat("Myproject.Controls.", "CustomControl1"));

if (null != t)
{
Control c = ((Control)(Activator.CreateInstance(t)));

// Then we can access the properties of the control by
// casting the it to the relevant type.
((Myproject.Controls.CustomControl1)c).ID = "ctrlCustomControl1";
}

No comments: