Passing parameters to Crystal Reports at runtime with c#


This small article shows how you can create and pass parameters value at runtime in a Crystal Report from your UI. In my application, I am using a ReportViewer control in Visual Studio 2005 to view the report.

Note: To learn more about how to generate reports in a ReportViewer, read this free book: Free Book: Reports using Report Viewer in Visual Studio 2005

 

The main functionality is defined in the ReportParameter method listed below. In this method, I create a ParameterFields object, which is a collection of parameters.

 

  ParameterFields paramFields = new ParameterFields();

       

After that, I create ParameterField, set its name and values and the value I pass is from the DropDownlList on my page. You can pass value from any control you want.

 

  ParameterField pfItemYr = new ParameterField();

  pfItemYr.ParameterFieldName = "year"; //year is Crystal Report Parameter name.

  ParameterDiscreteValue dcItemYr = new ParameterDiscreteValue();

  dcItemYr.Value = DropDownList1.SelectedValue;

  pfItemYr.CurrentValues.Add(dcItemYr);

       

 

After that I add parameter to the ParameterFields. If you have multiple parameters, you can create and add them using the similar process.

 

    paramFields.Add(pfItemYr);

 

The last step is to set ParameterFieldInfo property of the CrystalReportViewer control to ParameterFields I created.

 

        CrystalReportViewer1.ParameterFieldInfo = paramFields;

   

 

Here is the complete code of the page.

 

using  CrystalDecisions.CrystalReports.Engine;

using   CrystalDecisions.Shared;
 

public partial class _Default : System.Web.UI.Page

{

    SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["Hello"]);

    Class1 dbc = new Class1();

 

    protected void Page_Load(object sender, EventArgs e)

    {

        CrystalReportViewer1.LogOnInfo[0].ConnectionInfo.ServerName = "ShashiKantRay";

        CrystalReportViewer1.LogOnInfo[0].ConnectionInfo.UserID = "sa";

        CrystalReportViewer1.LogOnInfo[0].ConnectionInfo.Password = "sa";

        CrystalReportViewer1.LogOnInfo[0].ConnectionInfo.DatabaseName = "Shashi";

        ReportParameter();

    }

    private void ReportParameter()

    {

        CrystalReportViewer1.RefreshReport();

        ParameterFields paramFields = new ParameterFields();

        ParameterField pfItemYr = new ParameterField();

        pfItemYr.ParameterFieldName = "year"; //year is Crystal Report Parameter name.

        ParameterDiscreteValue dcItemYr = new ParameterDiscreteValue();

        dcItemYr.Value = DropDownList1.SelectedValue;

        pfItemYr.CurrentValues.Add(dcItemYr);

        paramFields.Add(pfItemYr);

        CrystalReportViewer1.ParameterFieldInfo = paramFields;

    }

}

 

 

Note: To learn more about how to generate reports in a ReportViewer, read this free book: Free Book: Reports using Report Viewer in Visual Studio 2005

 


Similar Articles