32.35 How can I create an instance of a Form class just from knowing its name in a string?


You can use the System.Reflection.Assembly.CreateInstance method to create a form from its name. Below is a code snippet. The name in the textbox has to be the full name including its namespace. So if there is a class named Form2 in namespace MyCompanyName, then the textbox would contain MyCompanyName.Form2. This snippet also assumes that the class is defined in the current executing assembly. If not, you would have to create an instance of the assembly that contains the class instead of calling the static method GetExecutingAssembly. As noted on this board, using reflection in this manner might affect performance.

You can download working samples (VB.NET, C#).

[C#]
     try
     {
          Assembly tempAssembly = Assembly.GetExecutingAssembly();
          // if class is located in another DLL or EXE, use something like
          // Assembly tempAssembly = Assembly.LoadFrom("myDLL.DLL");
          // or
          // Assembly tempAssembly = Assembly.LoadFrom("myEXE.exe");

          Form frm1 = (Form) tempAssembly.CreateInstance(textBox1.Text);// as Form;
          frm1.Show();
     }
     catch(Exception ex)
     {
          MessageBox.Show("Error creating: "+ textBox1.Text);
     }

[VB.NET]
     textBox1.Text = "MyNameSpace.Form2"
     ......

     Try
     Dim tempAssembly As System.Reflection.Assembly = System.Reflection.Assembly.GetExecutingAssembly()

      ' if class is located in another DLL or EXE, use something like
      ' tempAssembly = Assembly.LoadFrom("myDLL.DLL")
     ' or
     ' tempAssembly = Assembly.LoadFrom("myEXE.exe")

     Dim frm1 As Form = CType(tempAssembly.CreateInstance(textBox1.Text), Form) ' as Form;
      frm1.Show()
     Catch ex As Exception
          MessageBox.Show("Error creating: " + ex.ToString())
     End Try

© 2001-2010 Copyright Syncfusion Inc. All rights reserved.  |  Privacy Policy  |  Contact  |  Sitemap