Dynamically Add User Controls to a Form at Run Time?

Dynamically Add User Controls to a Form at Run Time?

Post by Stewart Ar » Tue, 02 Mar 2004 01:49:35


Is it possible to dynamically load a user control on a windows form similar
to the way you can load a web user control to an aspx page. Basically, I
would like the database to determine which controls are loaded to a form. I
am trying to mimic the IBuySpy portal functionality in a windows
application. Any ideas on how to do this?
 
 
 

Dynamically Add User Controls to a Form at Run Time?

Post by Stewart Ar » Tue, 02 Mar 2004 04:43:29

I found this:

You use System Reflection to dynamically load a control. If the DLL is named
"SpecControls.DLL" and the class you want is "SpecControls.ColorControl",
then use this code.

[C#]

// load the assembly
System.Reflection.Assembly assembly =
Assembly.LoadFrom("SpecControls.DLL");

// get the type
Type t = assembly.GetType("MyControls.MyControl");

// create an instance and add it.
//
Control c = (Control)Activator.CreateInstance(t);
parent.Controls.Add(c);

[VB.NET]

' load the assembly
Dim assembly1 As System.Reflection.Assembly =
Assembly.LoadFrom("SpecControls.DLL")

' get the type
Dim t As Type = assembly1.GetType("MyControls.MyControl")

' create an instance and add it.
'
Dim c As Control = CType(Activator.CreateInstance(t), Control)
parent.Controls.Add(c)

If you have any better ideas let me know!



similar
I