简体   繁体   中英

How to add Custom Control in a form dynamically

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()
    {

    }
 }
}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM