Crystal Reports: Setting values to report parameters using C#

Report Part

The first step consist in create a new report. To do it we’re gona click on File -> New -> Blank Report.

We click on Parameter Fields with the right mouse button and then in New:

 

 

A new window will appear with Create New Parameter as a title. Here we’re going to define the parameter options. In this tutorial we’re going to create two parameters, one as a string and one as a Boolean.

After creating our two parameters, Parameter Fields have to be similar as:

Code Part

In this part, we’re going to need these assemblies in our project:

using CrystalDecisions.Shared;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Web;

Also we need, in the front-end, a crystal report viewer similar to:

<CR:CrystalReportViewer ID="rptViewer" runat="server" AutoDataBind="true" Width="796px" PageZoomFactor="90" BestFitPage="True" HasCrystalLogo="True" HasDrilldownTabs="False" ToolPanelView="None" style="text-align:center" HasZoomFactorList="False" HasDrillUpButton="False" HasToggleGroupTreeButton="false" HasToggleParameterPanelButton="False" />

To proceed we are going to create a crystal report “in code”:

string rutaReport = "../reports/reportExample.rp";
ReportDocument rptDoc = new ReportDocument();
rptDoc.Load(rutaReport);

After that we should “connect” the report to the data base:

ConnectionInfo cInfo = new ConnectionInfo();
cInfo.UserID = "user";
cInfo.Password = "passwor";
cInfo.ServerName = "datasource";
ConectaReport(cInfo, rptDoc);

Now, let’s go to the parameter values. We have to create a parameter vector:

ParameterFields myParams = new ParameterFields();

And now we will put all the parameters (ParameterField) with their values (ParameterDiscreteValue) in it:

ParameterField myParam = new ParameterField();
ParameterDiscreteValue myDiscreteValue = new ParameterDiscreteValue();
myParam.ParameterFieldName = "paramOne";
myDiscreteValue.Value = "Value of the paramOne";
myParams.Add(myParam);
myParam = new ParameterField();
myDiscreteValue = new ParameterDiscreteValue();
myParam.ParameterFieldName = "paramTwo";
myDiscreteValue.Value = true;
myParams.Add(myParam);

And that’s all.

Tags: , , , , , , , ,