|
-
Apr 11th, 2003, 03:47 AM
#1
Thread Starter
Frenzied Member
create an instance of a Form class just from knowing its name in a string
I have seen this question here and there and didnt find a solution for it until recently (in SyncFusion )
So for those who may want to know:
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.
VB Code:
[C#]
try
{
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;
frm1.Show();
}
catch(Exception ex)
{
MessageBox.Show("Error creating: "+ textBox1.Text);
}
[VB.NET]
textBox1.Text = "MyNameSpace.Form2"
......
Try
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;
frm1.Show()
Catch ex As Exception
MessageBox.Show("Error creating: " + ex.ToString())
End Try
'Heading for the automatic overload'
Marillion, Brave, The Great Escape, 1994
'How will WE stand the FIRE TOMORROW?'
Eloy, Silent Cries and Mighty Echoes, The Vision - Burning, 1979
-
Apr 11th, 2003, 04:12 AM
#2
You can also do it like this:
VB Code:
Dim frm As Form = Activator.CreateInstance(Type.GetType("Namespace.ObjectName"))
frm.Show()
Which is basically the samething it just uses the Activator object instead of getting a reference to the current assembly.
Last edited by Edneeis; Apr 11th, 2003 at 04:17 AM.
-
Apr 11th, 2003, 05:05 AM
#3
Thread Starter
Frenzied Member
Thanks
'Heading for the automatic overload'
Marillion, Brave, The Great Escape, 1994
'How will WE stand the FIRE TOMORROW?'
Eloy, Silent Cries and Mighty Echoes, The Vision - Burning, 1979
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|