C# – passing parameters in crystal report

ccrystal-reports

I am creating crytal report from a stored procedure ,this works fine when i pass one parameter but it shows an error

"incorrect parameter "

when i pass two parameters
my code is

 {
    ReportDocument reportDocument = new ReportDocument();
    ParameterField paramField = new ParameterField();
    ParameterFields paramFields = new ParameterFields();
    ParameterDiscreteValue paramDiscreteValue = new ParameterDiscreteValue();

    paramField.Name = "@Dept";
    paramDiscreteValue.Value = TextBox1.Text.ToString();
    paramField.CurrentValues.Add(paramDiscreteValue);
    paramFields.Add(paramField);

    paramField.Name = "@Name";
    paramDiscreteValue.Value = TextBox2.Text.ToString();
    paramField.CurrentValues.Add(paramDiscreteValue);
    paramFields.Add(paramField);

    CrystalReportViewer1.ParameterFieldInfo = paramFields;
    reportDocument.Load(Server.MapPath("CrystalReport.rpt"));
    CrystalReportViewer1.ReportSource = reportDocument;
    reportDocument.SetDatabaseLogon("sa", "sa", "OPWFMS-7KYGZ7SB", "test");

}

please let me know any changes

Best Answer

You need to create new parameterField and value for both parameters. Your current code adds parameter, modifies it (change name and value) and adds same object again. This should be correct:

 {
ReportDocument reportDocument = new ReportDocument();

ParameterFields paramFields = new ParameterFields();
// ParameterDiscreteValue paramDiscreteValue = new ParameterDiscreteValue();

ParameterField paramField = new ParameterField();
ParameterDiscreteValue paramDiscreteValue = new ParameterDiscreteValue();
paramField.Name = "@Dept";
paramDiscreteValue.Value = TextBox1.Text.ToString();
paramField.CurrentValues.Add(paramDiscreteValue);
paramFields.Add(paramField);

paramField = new ParameterField(); // <-- This line is added
paramDiscreteValue = new ParameterDiscreteValue();  // <-- This line is added
paramField.Name = "@Name";
paramDiscreteValue.Value = TextBox2.Text.ToString();
paramField.CurrentValues.Add(paramDiscreteValue);
paramFields.Add(paramField);

CrystalReportViewer1.ParameterFieldInfo = paramFields;
reportDocument.Load(Server.MapPath("CrystalReport.rpt"));
CrystalReportViewer1.ReportSource = reportDocument;
reportDocument.SetDatabaseLogon("sa", "sa", "OPWFMS-7KYGZ7SB", "test");

}

EDIT: Error mentioned in comment is probably because there are two definitions of variable paramField or paramDiscreteValue in code. In one c# method you can't define variable with same name more than one time. Try code above as it is written and if you are still getting compiler error, please paste here full error text.

Related Topic