0
votes

I have a Subreport in main report named SubReport1 and it receives a Formula Field named SubReportFormula1.

To pass a value like this to the main report I just need to set:

ReportDocument Report = new ReportDocument();
Report.Load(RPTPath);
Report.DataDefinition.FormulaFields["MainReportFormula1"].Text = "'Hello'";
crystalReportViewer1.ReportSource = Report;

Even If I want to set a Parameter value in SubReport it's easy:

Report.SetParameterValue("SubReportParam1", "value 1", "SubReport1");

Question:

How to pass a Formula Field defined in a SubReport using Crystal Reports in C# (Visual Studio 2017)?

1

1 Answers

1
votes

To pass a value from the subreport back to the main report you will need to use a variable declared within a formula field that has a Shared scope. Variables can have one of 3 different scopes in Crystal Report (Local, Global, and Shared). Local variables may only be used within the same section, Global variables have a scope that spans sections, but only Shared variables can be used between subreports and the main report.

To create the variable you will need to create a new Formula Field within the Subreport. This formula field will need a formula similar to the following:

Shared StringVar foo;
foo := {@FormulaFieldName};

This formula will create a String type variable with the name "foo", and populate it with the value from another Formula Field named "FormulaFieldName". If you need a data type other than String, you can substitute the StringVar text with NumberVar or any other data type declaration that is supported by Crystal. Its rare to need more than String or Number data types though.

To access this variable within you main report you will need to create another new Formula Field in the main report. This new formula field will need a formula similar to the following:

Shared StringVar foo;

This formula field will retrieve the String variable named "foo" and display the value stored within the variable earlier.

You can also add additional lines of code to the formula if you need to concatenate or combine the value with another piece of data in your report.

There is a caveat to be aware of with these variables though. The subreport must be within a section of the report that is printed before any section of the report where the value of the variable is used. If you place the formula that retrieves the value of "foo" in a section prior to the section where the subreport is located, then "foo" has not been assigned a value yet and it will be treated as NULL.