Load WindowsFormsControlLibrary DLL from disk, then add to controls, C#

Viewed 114

How can I load a WindowsFormsControlLibrary UserControl from disk and then add it to the list of controls in a Windows Form at runtime programmatically?

I want to begin with nothing but a file name.

The fake code below illustrates. To be clear, I don't want to add it to the Visual Studio toolbox and use it at design-time. Instead, I want to load it at runtime, and insert it into a Windows Form without knowing anything about it but the file name.

    if (File.Exists("SomeUserControl.dll"))
    {
        // Load SomeUserControl.dll from disk
        // Do something to make it a control
        // ...
        UserControl SomeUserControl = new UserControl();
        Controls.Add(SomeUserControl);
    }
1 Answers

There are many examples online and questions here on so.
A very short example:

        // load your dll
        System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFrom("SomeUserControl.dll");

        // to get the right type use namespace.controlname
        Type type = assembly.GetType("MyControlLibrary.MyUserCtl");

        // create an instance
        object instanceOfMyType = Activator.CreateInstance(type);

        // do something with Control
        Control ctrl = instanceOfMyType as Control;
        if (ctrl != null)
        {
            this.Controls.Add(ctrl);
            ctrl.Dock = DockStyle.Bottom;
        }

and don't forget to wrap this inside try/catch

Related