Changing Values in a formula Field in Crystal .Net
One of the great aspects of programming in the .Net world is the robustness of the objects available. In particular I have found that manipulating a Crystal .Net report can be done in many ways with the Crystal.Engine namespace.
To demonstrate one way to manipulate objects in an already created report, I want to do a quick step through of changing a formula in a formula field. I have created a report with a formula field in the detail section that returns the value "Not December", or "December", if a date field month is December. This is the only formula field in the report, but there could be more, and the following code will show how to modify it.
First, I declared a variable as a formula field definition. I named the formula testFormula with the following formula:
|if Month (CurrentDate)=12 then "December" else "Not December" |
Next I create the report object, and then set the formula. While this demo only has one formula, code is provided that should work to allow you to find one formula in many.
Dim oRpt As New YourCrystalReport
Dim thisFormulaField As CrystalDecisions.CrystalReports.Engine.FormulaFieldDefinition
For Each thisFormulaField In oRpt.DataDefinition.FormulaFields
If thisFormulaField.FormulaName = "testFormula" Then
thisFormulaField.Text = "if Month (CurrentDate)=12 then " & _
"'December, Yes!' else 'December No.' "
CrystalReportViewer1.ReportSource = oRpt
This example creates a new instance of a report object that is in your Visual Studio project. There are other ways to do this, but that is for another topic. The report object is then loaded, and the data source is set to a dataset that I create in other code not shown here. Then, we loop through all the formulas in this report, looking for the formula name testformula. When it is found, using the text property, we set it to a new formula.
Feel free to play around with these formulas. One thing I haven't done yet is to add a formula programmatically to a report object. That may be a future article! If you have any questions or insights on this, or other articles, you can contact me at (remove dashes) corporatecoder-@-aspalliance.com
Eric Landes, your Corporate Coder