Search code examples
c#.netreflectioncompact-framework.net-assembly

How can I create variable controls at runtime?


I'm trying to create controls at runtime using Reflection. In my case, I get a string like Label or Button and I would like to create a object Label or Button of it.

Assembly WinFormasm = Assembly.Load("System.Windows.Forms,Version=2.0.000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");

Control label = (Control)Activator.CreateInstance(WinFormasm.GetType("System.Windows.Forms."+type));

When I execute this, I get the error:

File or assembly name 'System.Windows.Forms,Version=2.0.000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089', or one of its dependencies, was not found.

I don't realy know what is wrong there. I have also tried:

try
{
    Type cntrl = Type.GetType("System.Windows.Forms.Button,System.Windows.Forms, Culture=neutral, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089", true);
    label1.Text += cntrl.ToString() + " ";
}
catch(Exception e)
{
    label1.Text += e.ToString() + " ";
}

Trying this, I got an execution error: he can't create the type and returns null. If I change the gettype string into System.Int32, it works.

How can I create a control item using a string?


Solution

  • Your version number is wrong for System.Windows.Forms:

    var assembly = Assembly.Load("System.Windows.Forms, version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
    

    Then to create the desired control type, just specify the type name:

    var type = "Button";
    var control = (Control)Activator.CreateInstance(assembly.GetType("System.Windows.Forms." + type));