How can I create an instance of a class (form) with only it's name

R

Rene Mansveld

Hi,

how can I create an instance (object) of a class (form) if I only know the
classname (VB.NET 1.0)?
I need to do this in a complex app where jobs consist of parts. Each part's
data is saved in a separate database table. For the parts, the form's class
name is saved in a data table, so that I know which form to use. As this is
a string, I need to be able to create the form by it's name (like
CreateObject() does for COM objects).

--
Any help gladly appreciated!

Rene Mansveld
Spider IT - Germany
www.Spider-IT.de / www.Spider-IT.net

Please reply to the newsgroup(s) :blush:)
 
I

Imran Koradia

take a look at the Activator.CreateInstance method in the System.Reflection
namespace.

hope that helps..
Imran.
 
R

Rene Mansveld

Thanks for the quick answer!

Unfortunately I couldn't get this to work, and according to the help, this
will create an instance of a Type.
I tried the Activator.CreateInstance(Nothing, "Auftrag") call, but I got
this exception:
A non handled exception of type 'System.TypeLoadException' occured in
mscorlib.dll.
Extra info: The type Auftrag in the assembly ..., Version=0.3.1783.15723,
Culture=neutral, PublicKeyToken=null could not be loaded.
(translated from german)

Any ideas anyone?

--
Rene Mansveld
Spider IT - Germany
www.Spider-IT.de / www.Spider-IT.net

Please reply to the newsgroup(s) :blush:)
 
R

Rene Mansveld

It's solved now!

I got an answer from the german newsgroup from Jürgen Luhr which did it.
It is done through Reflexion:

'<deklaration code>
Imports System.Reflexion

'<routine code>
Dim t As Type = Type.GetType("<Namespace>.<Class>")
Dim c As ConstructorInfo = t.GetConstructor(Type.EmptyTypes)
Dim o As Object = c.Invoke(Nothing)
'Now o holds the instance of the class

--
Hope this helps ...

Rene Mansveld
Spider IT - Germany
www.Spider-IT.de / www.Spider-IT.net

Please reply to the newsgroup(s) :blush:)
 
K

KSI

Well - its the same with Activator.CreateInstance. You get the type object
from the namespace and class name and pass in the type object to the method:

Dim t As Type = Type.GetType("<Namespace>.<Class>")
Dim frm As Object = Activator.CreateInstance(t)
DirectCast(frm, Form).Show()


Imran.
 
H

Herfried K. Wagner [MVP]

Rene Mansveld said:
how can I create an instance (object) of a class (form) if I only know the
classname (VB.NET 1.0)?

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

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