Converting a string to a Form object

K

Kevin S Gallagher

I found this code (pretty sure it was from a MVP) for converting a string
variable to a form object which works fine within a form. Take the code and
place it into a code module and it fails on the second line in regards to
Me.GetType.... any idea how to get this to work outside of a form?

Dim strClass As String =
Reflection.Assembly.GetExecutingAssembly.GetName.Name & ".frmChildOne"
Dim tyOfStringVariable As Type =
Me.GetType().Assembly.GetType(strClass)
Dim frmObject As Object = Activator.CreateInstance(tyOfStringVariable)
Dim f As Form = CType(frmObject, Form)
With f
.ShowDialog()
.Dispose()
End With


Thanks for any insight!!!
 
P

PGC

Hi Kevin,

That's because "Me" refers to the instance of the form object the code was
originally placed in but a module is shared and doesn't have an instance. If
you're sure that you're only going to create a new standard windows form
object from the string provided then you could try;

Dim strClass as String =
Reflection.Assembly.GetExecutingAssembly.GetName.Name & ".frmChildOne"
Dim f As Form =
Reflection.Assembly.GetExecutingAssembly.CreateInstance(strClass)
With f
.ShowDialog()
.Dispose
End With

Note: The above will fail if the string (".frmChildOne") is not of type
windows.forms.form or the form doesn't exist. The module containing the
above code should stay with the same assembly as the forms you wish to
create from it.

Hope this helps.

PGC
 

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

Top