windowsforms-16975-controls-and-libraries-spreadsheet-examples-mail-merge-how-to-sort-data.md
When performing a mail merge with the SpreadsheetControl, you can specify the sort order in which data entries will appear in the resulting document. This document provides an example on how to specify sort criteria for multi-level detail data.
To get started with this tutorial, run the application created in the How to: Create a Master-Detail Report example. A master-detail template is automatically loaded into the SpreadsheetControl. This template contains a two-level detail range (click the Mail Merge Design View button in the Ribbon to show template ranges):
In each detail range, you can sort data by fields of the associated data member. In this example, sort top-level data by category name alphabetically, and specify two sort criteria for detail-level data - by product unit price in descending order (primary), and by product name in ascending order (secondary).
Select any cell within the Detail range (but outside of the DetailLevel0 nested range), and click the Sort Fields button on the Mail Merge tab, in the Sort & Group group. This invokes the Sort Fields dialog.
In the dialog, click New and select the CategoryName data field to be used as a criterion for sorting categories.
Define the Ascending sort order.
A sort field specified for a detail range in the mail merge template is a “SORTFIELD(n)” defined name, where (n) is the zero-based index of the sort field (sort fields are numbered consecutively throughout the template). The name of the data field specified as a sort criterion is assigned to the DefinedName.RefersTo property of the defined name, and the sort order is set to DefinedName.Comment.
A defined name that corresponds to a detail range holds all sort fields specified for this detail range in its DefinedName.Comment property (associated sort field names are divided by semicolon).
For example, after you have specified sort fields as described above, the following defined names are added…
| Name | RefersTo | Comment |
|---|---|---|
| SORTFIELD0 | “CategoryName” | Ascending |
| SORTFIELD1 | “UnitPrice” | Descending |
| SORTFIELD2 | “ProductName” | Ascending |
… and these sort fields are listed in the DefinedName.Comment property value of the defined names that specify detail ranges.
| Name | RefersTo | Comment |
|---|---|---|
| DETAILRANGE | Sheet1!$B$4:$D$10 | SORTFIELD0; |
| DETAILLEVEL0 | Sheet1!$B$9:$D$9 | SORTFIELD1;SORTFIELD2; |
Defined names specifying sort fields are added to the Worksheet.DefinedNames collection of the template worksheet.
Click the Mail Merge Preview button to review the result.
See Also