Passing parameter to Crystal Report in VB.NET

Here is how to pass a parameter value to a Crystal Report objet at runtime. There are two methods, depending if the report is to be exported as a file or opened with a viewer.
Required namespace:


Imports System.Collections.Generic
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared

EXAMPLE 1: parameter to a report exported as a file


'loading the report with dynamic data
myCrystalReport.Load()
myCrystalReport.SetDataSource(myDataSet)
myCrystalReport.Refresh()
'Passing the parameter
Dim param As New ParameterDiscreteValue
param.Value = "my value"
myCrystalReport.ParameterFields("parameterName").CurrentValues.Add(param)

'exporting as .PDF

myCrystalReport.ExportToDisk(ExportFormatType.PortableDocFormat, strFileName)

EXAMPLE 2 : parameter to a report opened with a crystal viewer:


'Loading the report with dynamic data
myCrystalReport.SetDataSource(myDataSet)
myCrystalReport.Refresh()

'Creating and binding the report viewer
Dim frmViewer As New CrystalDecisions.Windows.Forms.CrystalReportViewer()
frmViewer.ReportSource = myCrystalReport


'Passing the parameter
Dim oField As New ParameterField()
Dim oVal As New ParameterDiscreteValue()
oField.ParameterFieldName = "parameterName"
oVal.Value = " my parameter value "
oField.CurrentValues.Add(oVal)
frmViewer.ParameterFieldInfo.Add(oField)

'Showing the viewer
frmViewer.Show()

It works with Crystal Report 10.

No comments: