VB.net Declare as type by variable

  • Thread starter Thread starter This is A Fake Nickname
  • Start date Start date
T

This is A Fake Nickname

I want to launch a form within my app based on a command line.
Everything is great but:
The problem is that I can't have a variable for a form name that needs
to be launched. How do I use the value in a variable to be used as an
object? (the form)

Example:

Command line: AppName.exe FormName

Within the app the code:

dim LaunchingForm as New *FormName*
LaunchingForm.show
I need to fill in *FormName* with any form name I give it.

Thanks!
-JT
 
If the form "FormName" is defined within the your app AppName, you can do
something like this:

Dim myType as Type = Type.GetType(FormName)

Dim oObject = Activator.CreateInstance(myType)
DirectCast(oObject, Form).Show()

If the form is defined in another assembly, you'll need to pass in the fully
qualified name which includes the assembly to the GetType method.

hope this helps..
Imran.
 
* "This is A Fake Nickname said:
I want to launch a form within my app based on a command line.
Everything is great but:
The problem is that I can't have a variable for a form name that needs
to be launched. How do I use the value in a variable to be used as an
object? (the form)

Example:

Command line: AppName.exe FormName

Within the app the code:

dim LaunchingForm as New *FormName*
LaunchingForm.show
I need to fill in *FormName* with any form name I give it.

\\\
Dim frm As Form = _
DirectCast( _
Activator.CreateInstance( _
Type.GetType("MyApplication.SampleForm") _
), _
Form _
)
frm.Show()
///

- or -

\\\
Private Function CreateClassByName( _
ByVal PartialAssemblyName As String, _
ByVal QualifiedClassName As String _
) As Object
Return _
Activator.CreateInstance( _
[Assembly].LoadWithPartialName( _
PartialAssemblyName _
).GetType(QualifiedClassName) _
)
End Function
///

Usage:

\\\
Dim c As Control = _
DirectCast( _
CreateClassByName( _
"System.Windows.Forms", _
"System.Windows.Forms.Button" _
), _
Control _
)
With c
.Location = New Point(10, 10)
.Size = New Size(80, 26)
.Text = "Hello World"
End With
Me.Controls.Add(c)
///
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top