|
|
|||||||||
|
|||||||||
|
|||||||||
| |
|||
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
Calling a Form with a string in VB.NET
Hello,
I need to be able to display a form given only a string containing the name of the form. My first attempt looks something like this: Dim strFormName As String Dim objform As New Form strFormName = "frmTest1" objform = CreateObject(strFormName) objform.ShowDialog() I have a form named frmTest1. This gives me an error when CreateObject is executed. Of course, I know that I could just do this: Dim objForm1 as New frmTest1 Dim objForm2 as New frmTest2 Dim objForm2 as New frmTest3 ... Select case FormNumber case 1 objForm1.ShowDialog() case 2 objForm2.ShowDialog() case 3 objForm3.ShowDialog() case ... End Select But, I do not know whick form I need to display before this function is called. And declaring an instace of all of my app's forms is bringing my system to its knees. I need to find a way to only declare an instance of the form I need. Thank you for you help, Mike |
|
#2
|
|||
|
|||
|
Hi Mike,
AFAIK, you do this using reflection. Code:
Imports System Imports System.Windows.Forms Imports System.Reflection Public Class ObjectFinderPublic Shared Function CreateObjectInstance(ByVal objectName As String) As Object ' Creates and returns an instance of any object in the assembly by its type name. Dim obj As Object TryReturn obj End Function Public Shared Function CreateForm(ByVal formName As String) As Form ' Return the instance of the form by specifying its name.If objectName.LastIndexOf(".") = -1 Then 'Appends the root namespace if not specified.Catch ex As ExceptionobjectName = [Assembly].GetEntryAssembly.GetName.Name & "." & objectNameEnd If obj = [Assembly].GetEntryAssembly.CreateInstance(objectName)obj = NothingEnd TryReturn DirectCast(CreateObjectInstance(formName), Form)EndFunctionEnd Class Then all you need to do is make a call like this in your code: Code:
Dim frm As Form = ObjectFinder.CreateForm("MyForm")
HTH, -Beth |
![]() |
| Viewing: Dev Articles Community Forums > Programming > .NET Development > Calling a Form with a string in VB.NET |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|