Live Chat Icon For mobile
Live Chat Icon

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

Platform: WinForms| Category: Form

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#).

    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;
  catch(Exception ex)
    MessageBox.Show(''Error creating: ''+ textBox1.Text);

  textBox1.Text = ''MyNameSpace.Form2''

  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;
  Catch ex As Exception
    MessageBox.Show(''Error creating: '' + ex.ToString())
  End Try

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.