Using Reflection.Assembly to Load Forms from a Table

Thiscode sample is going to make your day. The scenario where this codecould be quite helpful is where you are fetching a form name from thedatabase and would like to open that form by passing the name as astring variable. To accomplish this task you will have to use theSystem.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());
}




Notethat the form name in the textbox should include its completenamespace. For example, "Project1.Formname" or "Inventory.frmItem".

Twitter Digg Delicious Stumbleupon Technorati Facebook Email

No comments yet... Be the first to leave a reply!