The concept of Text Control Reporting is to accept pre-shaped data. That means that Text Control's MailMerge component is merging the data rows 'as-is' and data shaping, sorting or queries are done in the application business layer.
Sometimes, it is required to define the order of data rows in the template. This sample shows how to realize this concept based on additional parameters in the merge block name and LINQ to sort the data rows.
Let's have a look at the XML data source. It consists of 2 simple tables: company and product and a relation between those tables.
The template simply consists of a single merge block with the name product. Without any sorting, the results would look like this:
In order to enable sorting, we simply introduce a new parameter to the merge block name:
The sample code shows how to detect and parse these merge blocks in the template and how to replace the rows of the relevant DataTables with sorted DataRows.
The class DataSelector is parsing the template in order to sort the given data source. The property Template returns the changed template which is loaded into a MailMerge instance using LoadTemplateFromMemory. Finally, the document is merged with the sorted DataSet:
The DataSelector class loops through all merge blocks in a given template to check for specific keywords. A temporary ServerTextControl instance is used to recognize blocks with the sorting keyword 'ORDERBY'. If such tagged merge blocks are found, the parameters are parsed, stored and the block name is reset to the original block name.
Finally, LINQ is used to sort the data rows by the given column name. The resulting data rows are replaced in the specific DataTable. The DataTable won't be replaced completely to keep existing data relations and constraints.
Let's do two examples. The merge block name contains the following string:
The ascending sorted results are shown below:
Descending sorting results:
LINQ is used to sort the results to show the flexibility. You can customize this process with your own selectors. This shows the flexibility and the power of the MailMerge class. Give it a try to download the sample project directly from GitHub.
Download the sample from GitHub and test it on your own.