Search Forum
(57415 Postings)
Search Site/Articles

Archived Articles
712 Articles

C# Books
C# Consultants
What Is C#?
Download Compiler
Code Archive
Archived Articles
Advertise
Contribute
C# Jobs
Beginners Tutorial
C# Contractors
C# Consulting
Links
C# Manual
Contact Us
Legal

GoDiagram for .NET from Northwoods Software www.nwoods.com


              
Printable Version

Using Reflection.Assembly to Load Forms from a Table
By Syed Irtaza Ali

n

This code sample is going to make your day. The scenario where this code could be quite helpful is where you are fetching a form name from the database and would like to open that form by passing the name as a string variable. To accomplish this task you will have to use the System.Reflection.Assembly class.

[C#]


using System.Reflection;
...
...
...
try {
Assembly myAssembly = Assembly.GetExecutingAssembly();
Form myForm = myAssembly.CreateInstance(txtFormName.text) as Form;
myForm.ShowDialog();
}
catch (System.NullReferenceException exNull) {
MessageBox.Show ("Invalid Form name. Please note that Form names " +
"are case sensitive.", "Form not found");

System.Diagnostics.Trace.WriteLine("-*-*-*-*-*-*-*-*-*-*-*-*-*-*-" +
Environment.NewLine + "Project Load" +
Environment.NewLine + exNull.ToString());
}
catch (Exception ex) {
MessageBox.Show (ex.ToString());
}
...
...




Note that the form name in the textbox should include its complete namespace. For example, "Project1.Formname" or "Inventory.frmItem".