65.9K
CodeProject is changing. Read more.
Home

Reflection

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Nov 20, 2014

CPOL

2 min read

viewsIcon

8492

Methods used to load the required Windows form dependant on the result of a SQL query

I recently came across an issue where I needed to load a particular Windows Form dependant on the result of a SQL query. After some amount of time Googling and asking a question on StackOverflow, I finally found the answer in the System.Reflection namespace.

This post will explain the methods I used to load the required form.

The System.Reflection namespace examines metadata to retrieve information about assemblies, modules and members, etc. Below is the code I used to achieve what was required.

//Retrieve form name from SQL database. 
string formName = dr["formname"].ToString(); 
string assemblyName = Assembly.GetExecutingAssembly().GetName().Name; 
string componentName = assemblyName + "." + formName; 
Type type = Type.GetType(componentName, false, true); 
ConstructorInfo ci = type.GetConstructor(new Type[0] { }); 
object[] argVals = new Object[] { }; 
Form form = (Form)ci.Invoke(argVals); 
form.Show();

I will now proceed to explain each line of code and what it does when executed.

Firstly, I retrieved the form name that I needed to open from the SQL database and placed it into a variable called “formName”. This will be used later on to build the “componentName” to pass to the “GetType” method.

I then declared a variable called “assemblyName” which stores the name of the assembly of the code that is currently executing.

string assemblyName = Assembly.GetExecutingAssembly().GetName().Name;

I then proceeded to build the “componentName” which combines the “assemblyName” and the “formName”, which will now be passed to the “GetType” method. The result of the “componentName” within my project will be – “Reflection.Form2”. “Reflection” is the namespace of the project and “Form2” is the name of the form.

The next line Type type = Type.GetType(componentName, false, true); sets a variable name “type” to the type of the “componentName” variable which was set earlier on. The other two parameters that are passed are “throwOnError” and “ignoreCase”.

The “ConstructorInfo” line provides access to the constructor metadata and allows us to configure the form to accept information such as parameters on execution by setting the type of parameter to expect.

The “argVals” array allows us to store the parameters or information that needs to be passed to the opening form.

Form form = (Form)ci.Invoke(argVals); The code to the left sets a variable of the type Form to the form we wish to open using the reflection code above.

Lastly “form.Show()” instructs the application to open.