Load UserControl With Reflection

From Visual WebGui Wiki
Jump to: navigation, search
VWG 64+ The content of this article is valid for version 6.4 and later, including v7.x;
Code sample projects are written in Visual Studio 2012 for v7.x, unless otherwise noted

Contents

Load UserControl using reflection

This article explains how to load a UserControl to a Visual WebGui application in run-time from an assembly that is not referenced in your project. The way this is done in .NET is with Reflection.

Code samples

C# Code

string strBaseDir = AppDomain.CurrentDomain.BaseDirectory;
string strSlnDir = strBaseDir.Remove(AppDomain.CurrentDomain.BaseDirectory.LastIndexOf(@"\UserControlLoadInRunTime"));
string strPathToAsm = Path.Combine(strBaseDir, @"WebGUIControlLibrary\bin\Debug\WebGUIControlLibrary.dll");
try
{
    Assembly objAsm = Assembly.LoadFile(strPathToAsm);
    object objTemp = objAsm.CreateInstance("WebGUIControlLibrary.UserControl1");
    Gizmox.WebGUI.Forms.UserControl objUserControl = objTemp as Gizmox.WebGUI.Forms.UserControl;
 
    if (objUserControl != null)
    {
        this.Controls.Add(objUserControl);
    }
}
catch(Exception objException)
{
    // do something
}

VB.NET Code

Dim strBaseDir As String = AppDomain.CurrentDomain.BaseDirectory
Dim strSlnDir As String = strBaseDir.Remove(AppDomain.CurrentDomain.BaseDirectory.LastIndexOf("\UserControlLoadInRunTime"))
Dim strPathToAsm As String = Path.Combine(strBaseDir, "WebGUIControlLibrary\bin\Debug\WebGUIControlLibrary.dll")
Try
    Dim objAsm As Assembly = Assembly.LoadFile(strPathToAsm)
    Dim objTemp As Object = objAsm.CreateInstance("WebGUIControlLibrary.UserControl1")
    Dim objUserControl As Gizmox.WebGUI.Forms.UserControl = TryCast(objTemp, Gizmox.WebGUI.Forms.UserControl)
 
    If objUserControl IsNot Nothing Then
        Me.Controls.Add(objUserControl)
    End If
Catch objException As Exception
    ' do something
End Try

The demo application

The demo application is supplied both in C# and VB.NET code.

Down.gif Download for VS 2012


VWG 64 The following section is valid only for version 6.4;

Down.gif Download for VS 2005 and 2008