Welcome to WindowsClient.net | Sign in | Join

Here are some frequently asked questions about Windows Forms and their answers.

Windows Forms FAQs

How do I create an instance of a Form class from its name?

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

try 
{ 
  Assembly assembly = Assembly.GetExecutingAssembly(); 
  // if class is located in another DLL or EXE,
  // then use Assembly.LoadFrom("myDLL.DLL"); 
  Form form = (Form) assembly.CreateInstance( textBox1.Text );
  form.Show(); 
} 
catch ( Exception ex ) 
{ 
  MessageBox.Show( "Error creating: " + textBox1.Text ); 
}

Contributed from George Shepherd's Windows Forms FAQ



Page view counter