6

MailMerge: Merging Hyperlinks using the FieldMerged Event

 1 year ago
source link: https://www.textcontrol.com/blog/2022/06/08/mailmerge-merging-hyperlinks-using-the-fieldmerged-event/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Merging Hyperlinks using the FieldMerged Event

The MailMerge class is used to merge data into merge fields, image placeholders, merge blocks, barcodes and other reporting elements. By default, MS Word compatible MergeFields and FormFields are merged automatically in loaded templates. But consider a template where a hyperlink should be merged with a dynamic website address.

The Template

In the following screenshot, a simple template is created using TX Text Control that consists of 2 merge fields:

  • company
  • website
Template in TX Words

The Data Source

The following class is used to create the data source object for this sample merge process:

Pay attention to the Hyperlink class that contains the actual display Text and the Target. The overridden ToString method returns the text, so that without any custom handling, the merge field would contain the display text after the merge process.

After creating an instance of the data source, the MailMerge class is used to merge the data object into the template:

Custom Event Handling

In our custom handling, we want to replace the merge field website with a clickable hyperlink. Therefore, the FieldMerged event is used to inject the custom handling.

The FieldMerged event is triggered for all merged fields. The event not only returns the MailMergeFieldAdapter that contains information about the merged field, but gives also access to the actual DataRow that is used to merge data into the current field. In the event handler, we check whether the returned DataRow object is a custom Hyperlink object:

In case, the object is a Hyperlink, a temporary ServerTextControl is used to generate a new hyperlink with the same format (font, color, ...) that is eventually returned to the MergedField property.

In the resulting document, the website merge field is converted into a clickable hypertext link:

Merged Hyperlink

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK