Reputation: 447
I have a program wherein I am adding controls
dynamically. Control type is based on a value in database
. For example if the value in Database
is Label
then the program creates the control dynamically.
Creating controls dynamically is working great. I am using below function:
Type typeFrm = typeof(Form);
Assembly assb = typeFrm.Assembly;
Type controlType = assb.GetType("System.Windows.Forms." + strType);
object obj = Activator.CreateInstance(controlType);
Control control = (Control)obj;
return control;
then Control ctrl = CreateControl(strCtrlType);
Other code is to setup the control location, width, height etc ect.
My question is I have a custom control
and how will add it to the form dynamically? I tried the function above and change the line:
Type controlType = assb.GetType("System.Windows.Forms." + strType);
to
Type controlType = assb.GetType("CustomCtrl." + strType);
But its not working. The function always return null
.
See sample custom control code.
namespace CustomCtrl
{
public class CButton : Button
{
public CButton() : base()
{
}
}
}
Upvotes: 1
Views: 206
Reputation: 26989
Here is how to get the type from an assembly. Imagine you have a class with full name (class name + namespace) SomeNamespace.SomeClass
within a dll named Some.dll
:
Type type = Type.GetType("SomeNamespace.SomeClass,
Some"); // without .dll
So in your case it will be:
Type type = Type.GetType("CustomCtrl.CButton,
DllWhereCButtonIs"); // without .dll
Upvotes: 3
Reputation: 8841
Type.GetType("namespace.Type")
only works when the type is present in mscorlib.dll or the currently executing assembly.If not of those things is true, you should use system.type.assemblyqualifiedname
https://msdn.microsoft.com/en-us/library/system.type.assemblyqualifiedname.aspx
Upvotes: 1