The MailMerge class provides some additional properties and methods that allow to further customize the mail merge process.
Using Mapped Fields
The MailMerge class allows to automatically map between names of fields in your data source and names of mail merge fields in the document. To perform that, use the MailMerge.MappedDataFields property that returns a MappedDataFields object. MappedDataFields is a collection of string keys into string values. The keys are the names of mail merge fields in the document and the values are the names of fields in your data source. The class provides all properties and methods typical for a regular .NET collection such as Add, Clear, Remove etc.
Example MailMergeMappedDataFields
Shows how to add a mapping when a merge field in a document and a data field in a data source have different names.
[C#]
doc.MailMerge.MappedDataFields.Add("MyFieldName_InDocument", "MyFieldName_InDataSource");
[Visual Basic]
doc.MailMerge.MappedDataFields.Add("MyFieldName_InDocument", "MyFieldName_InDataSource")
[Java]
doc.getMailMerge().getMappedDataFields().add("MyFieldName_InDocument", "MyFieldName_InDataSource");
Obtaining Merge Field Names
You can get a collection of the merge field names available in the document. Call MailMerge.GetFieldNames that returns an array of string that contains the names. The method supports extended syntax in field names. A new string array is created on every call. The method does not eliminate duplicate field names.
Example MailMergeGetFieldNames
Shows how to get names of all merge fields in a document.
[C#]
string[] fieldNames = doc.MailMerge.GetFieldNames();
[Visual Basic]
Dim fieldNames As String() = doc.MailMerge.GetFieldNames()
[Java]
String[] fieldNames = doc.getMailMerge().getFieldNames();
Deleting Merge Fields
If your mail merge operation does not always need to populate all fields in the document, you could use MailMerge.DeleteFields to remove all remaining mail merge fields. This method removes MERGEFIELD and NEXT fields from the document.
Example MailMergeDeleteFields
Shows how to delete all merge fields from a document.
[C#]
doc.MailMerge.DeleteFields();
[Visual Basic]
doc.MailMerge.DeleteFields()
[Java]
doc.getMailMerge().deleteFields();
Removing Empty Paragraphs
Sometimes you may need to remove paragraphs that contained mail merge fields with no data from the document. Just set MailMerge.RemoveEmptyParagraphs to true.
Example MailMergeRemoveEmptyParagraphs
Shows how to make sure empty paragraphs that result from merging fields with no data are removed from the document.
[C#]
doc.MailMerge.RemoveEmptyParagraphs = true;
[Visual Basic]
doc.MailMerge.RemoveEmptyParagraphs = True
[Java]
doc.getMailMerge().setRemoveEmptyParagraphs(true);