Malik
Malik

Reputation: 217

Vb.Net Get Report Name from String

I have different Crystal Reports in my project like:

RptHbl RptUBL RptMCB RptBAF

and so on...

Now I have a string with one of the report name which it gets from database Like:

Dim Myrptname = "RptHbl"

Now I want to load a Report, for which i usually use the following code to initialize the report

Dim Myrpt As New RptHbl

Now how I can use a report name which is stored in string Myrptname Like Dim Myrpt as New "MyrptName"??????? Thanks

Upvotes: 2

Views: 639

Answers (1)

Steven Doggart
Steven Doggart

Reputation: 43743

First, you need the full name of the report class, so if the name in the database is just the class name, you'll need to append the namespace:

Dim reportName As String = "RptHbl"
Dim fullTypeName As String = "MyNamespace." & reportName ' Consider using the NameOf operator

Next, you can use Assembly.GetType which uses reflection to find the type (i.e. the class) by the full name. However, first you need to get a reference to the right assembly. If your reports are in the same assembly, you can do it like this:

Dim reportAssembly As Assembly = Assembly.GetCallingAssembly()
Dim reportType As Type = reportAssembly.GetType(fullTypeName)

However, if the reports are in a different assembly, then, as long as you have a reference to one of them, you could do it like this:

Dim reportAssembly As Assembly = GetType(RptHbl).Assembly
Dim reportType As Type = reportAssembly.GetType(fullTypeName)

Once you have that Type object that describes the report class, you can create an instance of it using the Activator.CreateInstance method, like this:

Dim report As Object = Activator.CreateInstance(reportType) 

I don't know enough about Crystal Reports to know, but I would assume that all report classes are derived from some base class. For the sake of example, let's just assume that they all inherit from a base class called Report. If so, then you can cast the new instance to that base type, like this:

Dim report As Report = DirectCast(Activator.CreateInstance(reportType), Report)

So, to put it all together, you could do something along these lines:

Function CreateReport(name As String) As Report
    Dim reportTypeName As String = "MyNamespace." & name
    Dim reportAssembly As Assembly = Assembly.GetCallingAssembly()
    Dim reportType As Type = reportAssembly.GetType(reportTypeName)
    Return DirectCast(Activator.CreateInstance(reportType), Report)
End Function

Upvotes: 1

Related Questions