converting string to object

E

excelleinc.com

Hi,

I want to have a sub that takes string as argument and then opens a form
that has that string as a class name.

Say:

Class users
Inherits System.Windows.Forms.Form
'display form content
End Class

Sub functions(str As String)
Dim frm As New str 'this is want I'm trying to accomplish - obviously
doesn't work this way
frm.ShowDialog()
End Sub

And then call it as Sub("users") If I want to accomplish next:
Dim frm As New users
frm.ShowDialog()


Obviously, what I'm trying to do is much more complicated but if I would
know how to accomplish example above I'd be able to do what I need.


Thanks,

Vlado


http://www.excelleinc.com
 
D

Daniel Klein

Obviously, what I'm trying to do is much more complicated but if I would
know how to accomplish example above I'd be able to do what I need.

Look up Activator.CreateInstance() method in the MSDN.

Daniel Klein
 
I

Imran Koradia

You'll need to use reflection:

Imports System.Reflection

Sub ShowForm(str As String)
Dim ty As Type = Type.GetType(str)
Dim frm As Object = Activator.CreateInstance(ty)
DirectCast(frm, Form).ShowDialog()
End Sub


Then call the above method as:
ShowForm("MyApplication.users")

Note that the method Type.GetType requires a fully qualified name including
namespace. Since by default Vb.NET adds the project as the default namespace,
you would need to append it to the form name before passing it as a parameter
to Type.GetType (assuming you are using the default settings only). I would
suggest reading up on the documentation of Type.GetType to make sure you
don't end up with null references.


hope that helps..
Imran.
 
E

excelleinc.com

Worked great.

I was getting null references but when I turned IgnoreCase to True
Dim ty As Type = Type.GetType(Str, False, True)
everything worked just great.

Thank you both very much.
 

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