Wednesday, May 12, 2004

Using Parameters With Crystal Reports

To use parameters with Crystal Reports, there seems to be two fundamental issues to deal with:
  • Create parameters on the report (.rpt)

  • Set parameters on the report viewer object before assigining the report.

For example, I have a report that needs to filter data based on a date range. So in the report I had to:
  1. Create the parameters, BeginDate & EndDate

  2. Using the Select Expert, apply the parameters to the selection criteria (this is actually very easy; once the parameters have been created, you can select them from the drop-downs in Select Expert).

  3. Drag and place the parameters onto the report. This step is not required, but I find that most reports need to represent how the underlying data was selected.

Now that the report has parameters, it must have some way of aquiring values for the parameters at run-time. This is the point at which I had the most trouble because I thought that the code should set the parameters on the report object at run-time. That doesn't work. It does work, however, if you add parameter values to the viewer object prior to handing the report to the viewer. The general method to follow is:
  1. Create one ParameterField object per parameter on the report.

  2. IMPORTANT: Set each ParameterField.ParameterFieldName property to the same name as the associated parameter in the report. If the names are not an exact match, then the report will not aquire the parameter value correctly.

  3. Add the each ParameterField to a ParameterFields object.

  4. Assign the ParameterFields object to the viewer's ParameterInfo property.

  5. Finally, assign the report to the viewer. (Actually the order of report and parameters assignment is not significant, but it is a little more logical)

Here's a simple C# code snippet from a web form's Page_Load event handler:


CrystalDecisions.Shared.ParameterField fld = new ParameterField();
CrystalDecisions.Shared.ParameterFields flds = new ParameterFields();

// Set begin date param
CrystalDecisions.Shared.ParameterDiscreteValue prmBeginDate =
new CrystalDecisions.Shared.ParameterDiscreteValue();
prmBeginDate.Value = new DateTime( 2004, 1, 2 );
// NOTE: the parameter name must match the report's parameter
// name exactly.
fld.ParameterFieldName = "BeginDate";
// Add the discrete param to the param field
fld.CurrentValues.Add( prmBeginDate );
// Add the param fld to the param fld collection
flds.Add( fld );

// Add the params to the viewer
// snippet info: crv is a class member declared as CrystalDecisions.Web.CrystalReportViewer
crv.ParameterFieldInfo = flds;

// Add the params to the viewer
crv.ParameterFieldInfo = flds;

// Now load the report
OverallEquipmentActivity2 rpt = new OverallEquipmentActivity2();
crv.ReportSource = rpt;


No comments: