When using RDLC to develop reports, if the data source content is as follows.
Copy codeThe Code is as follows:
Private List <UserData> CreateDataSet ()
{
List <UserData> userDataSet = new List <UserData> ();
UserDataSet. Add (new UserData () {Name = "Clark", Age = 18 });
UserDataSet. Add (new UserData () {Name = "Yaya", Age = 15 });
Return userDataSet;
}
We can quickly use the data table control in RDLC to present data in reports.
However, when the customer requires a report, the data source content should be displayed in one row. RDLC processing is not that simple, because RDLC does not have the function of loop processing. The developer must use a hidden list and an external string to combine data... And so on. However, there are no efficiency and many restrictions for such development.
This problem has plagued me for several days. I slept halfway last night and suddenly got inspiration. You can use the Sum function in RDLC to process data loops.
The Sum function retrieves each piece of data in the dataset and calculates the Sum of all data. We can write the expression as the following function, and use the code. PushStringStack RDLC custom function to let the Sum function get all the data. In this way, each piece of data in the dataset can be handed over to code. PushString for processing once.
Copy codeThe Code is as follows:
= Sum (code. PushString (Fields! Name. Value, Fields! Age. Value), "UserDataSet ")
Next, let's look at the RDLC custom function code. PushString, which uses a Static string variable to record the results after each data processing. Developers can understand that this method is to process data cyclically.
Copy codeThe Code is as follows:
Public Shared _ foreachResult As String = String. Empty
Public Shared Function PushString (userName As String, userAge As String) As Integer
_ ForeachResult + = userName & "(" & userAge &"),"
Return 0
End Function
Of course, after processing the data in a loop, you still need to display the data on the screen. A code. PopString callback is created.
Copy codeThe Code is as follows:
Public Shared Function PopString () As String
Return _ foreachResult
End Function
And rewrite the original expression:
Copy codeThe Code is as follows:
= IIF (Sum (code. PushString (Fields! Name. Value, Fields! Age. Value), "UserDataSet") <> 0, "", code. PopString ())
After compilation and execution, you can see that the data format required by the customer is correctly displayed in the RDLC text box.
Sample program: RdlcForeachDataSample_jb51net click here to download.