Tip: How to pass Crystal Report Parameters Programmatically?

You can pass parameter values to a crystal report programmatically using ReportDocument.DataDefinition.ParameterFields member, which represents a collection of parameters associated with a report.
 
Before you use ParameterFields, you must import CrystalReport.Engine namespace by adding the following line to your code:
  1. Imports CrystalDecisions.CrystalReports.Engine 
In my report, I have two parameters called ParameterName1 and ParameterName2 and I want to pass values as "Parameter1Value" and "Parameter2Value" respectively. If you have more than 2 parameters, just repeat the same steps between "START" and "END" commented lines. Also, read the comments in the code carefully.
  1. ' Create a report instance. This is the class added to your project  
  2. ' when you added the report to the project  
  3. Dim report As MyReport = New MyReport  
  4.    
  5. ' Fill data in DataSet here. Skip this step if your report is calling  
  6. ' a stored procedure direct  
  7. Dim ds As DataSet = New DataSet  
  8. ' ds = GetDataFromDatabase()  
  9.    
  10. Dim crParameterDiscreteValue As ParameterDiscreteValue  
  11. Dim crParameterFieldDefinitions As ParameterFieldDefinitions  
  12. Dim crParameterFieldLocation As ParameterFieldDefinition  
  13. Dim crParameterValues As ParameterValues  
  14.          
  15. '  
  16. ' Get the report parameters collection.  
  17. '  
  18. crParameterFieldDefinitions = report.DataDefinition.ParameterFields  
  19.    
  20. ' Add a parameter value - START  
  21. crParameterFieldLocation = crParameterFieldDefinitions.Item("@ParameterName1")  
  22. crParameterValues = crParameterFieldLocation.CurrentValues  
  23. crParameterDiscreteValue = New CrystalDecisions.Shared.ParameterDiscreteValue  
  24. crParameterDiscreteValue.Value = "Parameter1Value"  
  25. crParameterValues.Add(crParameterDiscreteValue)  
  26. crParameterFieldLocation.ApplyCurrentValues(crParameterValues)  
  27. ' Add a parameter value - END  
  28.    
  29. crParameterFieldLocation = crParameterFieldDefinitions.Item("@ParameterName2")  
  30. crParameterValues = crParameterFieldLocation.CurrentValues  
  31. crParameterDiscreteValue = New CrystalDecisions.Shared.ParameterDiscreteValue  
  32. crParameterDiscreteValue.Value = "Parameter2Value"  
  33. crParameterValues.Add(crParameterDiscreteValue)  
  34. crParameterFieldLocation.ApplyCurrentValues(crParameterValues)  
  35.    
  36. '  
  37. ' Set report's DataSource. Skip this step if your report is calling a   
  38. ' stored procedure direct in the report.  
  39. '  
  40. report.SetDataSource(ds)  
  41.    
  42. '  
  43. ' Set CrystalReportViewer.ReportSource  
  44. '  
  45.    
  46. CrystalReportViewer1.ReportSource = report