Thursday, November 5, 2009

c# Crystal Reports Parameter Fields Notes

When I was working on some crystal reports related projects in Visual Studio 2008 I kept getting the following error:


CrystalDecisions.CrystalReports.Engine.ParameterFieldCurrentValueException: Missing parameter values. ---> System.Runtime.InteropServices.COMException (0x8004100E): Missing parameter values.
After going through my code and looked at online samples, I still couldn't figured out what's wrong. Below is my original code


Report rpt = new Report();
ParameterValues crParamValues = new ParameterValues();
ParameterDiscreteValue crParamGrpName = new ParameterDiscreteValue();
crParamGrpName.Value = "value";
crParamValues.Add(crParamGrpName);
rpt.DataDefinition.ParameterFields[0].ApplyCurrentValues(crParamValues);
rpt.SetDataSource(ds);
rpt.ExportToDisk(pdfFormat, filePath);

After much fiddling and googling, I finally found out what was the problem. It seems that in Visual Studio 2008, you need to set data source BEFORE setting parameters, not after. Once I set data source first everything exported fine. Also I realized that the code I used to set parameters can be replaced by just one line. So the final code becomes

rpt.SetDataSource(ds);
rpt.SetParameterValue(0, grpName);
rpt.ExportToDisk(pdfFormat, filePath);
Looks much nicer right?

No comments: