Pass parameters into a Crystal Report from VB.NET

You can programmatically pass parameter values into your Crystal Report using VB.NET code similar to this:

    Imports CrystalDecisions.CrystalReports.Engine
    Imports CrystalDecisions.Shared
    '
    ' Load the selected report file.
    '
    Dim CR As New ReportDocument
    CR.Load(strReportPath)
    '
    ' Declare the parameter related objects.
    '
    Dim crParameterDiscreteValue As ParameterDiscreteValue
    Dim crParameterFieldDefinitions As ParameterFieldDefinitions
    Dim crParameterFieldLocation As ParameterFieldDefinition
    Dim crParameterValues As ParameterValues
    '
    ' Get the report's parameters collection.
    '
    crParameterFieldDefinitions = CR.DataDefinition.ParameterFields
    '
    ' Set the first parameter
    ' - Get the parameter, tell it to use the current values vs default value.
    ' - Tell it the parameter contains 1 discrete value vs multiple values.
    ' - Set the parameter's value.
    ' - Add it and apply it.
    ' - Repeat these statements for each parameter.
    '
    crParameterFieldLocation = crParameterFieldDefinitions.Item("StartDate")
    crParameterValues = crParameterFieldLocation.CurrentValues
    crParameterDiscreteValue = New CrystalDecisions.Shared.ParameterDiscreteValue
    crParameterDiscreteValue.Value = strStartDate
    crParameterValues.Add(crParameterDiscreteValue)
    crParameterFieldLocation.ApplyCurrentValues(crParameterValues)
    '
    ' Set the Crytal Report Viewer control's source to the report document.
    '
    CrystalReportViewer.ReportSource = CR

If your report's DataSource is a .NET DLL DO NOT set the ReportDocument's DataSource property programatically as in the code below. However, if the DataSource is an XML Schema (.xsd) file you must set it prior to setting your parameters.

    cr.SetDataSource(DS.Tables("Customer"))

If your report's DataSource is a .NET DLL as shown here and the public functions that return the datatables available to your report where changed to require parameters, as illustrated below, the parameters can be set as just described.

    Public Function Customers(theStartDate As String) As DataTable

If the parameters were added to your Crystal Report by clicking the Parameter Fields node in the Crystal IDE's Field Explorer they can be set using the following code:

    Dim cr As New ReportDocument
    cr.Load(strReportPath)
    cr.SetDataSource(DS.Tables("Customers"))
    cr.SetParameterValue("StartDate", strMyParmValue)
    CrystalReportViewer.ReportSource = cr

To learn about using the Crytal Report Viewer control click here.




About TheScarms
About TheScarms


Sample code
version info

If you use this code, please mention "www.TheScarms.com"

Email this page


© Copyright 2024 TheScarms
Goto top of page