2

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);
    }
Ray White
  • 297
  • 4
  • 19
  • Possible duplicate of [Loading DLLs at runtime in C#](https://stackoverflow.com/questions/18362368/loading-dlls-at-runtime-in-c-sharp) – JohnG Oct 17 '19 at 02:22
  • and here as well: https://stackoverflow.com/questions/465488/can-i-load-a-net-assembly-at-runtime-and-instantiate-a-type-knowing-only-the-na – ralf.w. Oct 17 '19 at 07:10

1 Answers1

1

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

ralf.w.
  • 1,676
  • 1
  • 24
  • 34