TX Text Control supports all MS Word fields including the typical merge fields, content control fields, legacy form fields or special fields such as DOCVARIABLE. All of those fields can be found in the ApplicationField collection.

For the most typical fields, FieldAdapters are available to create and handle MS Word compatible fields directly.

The MailMerge class populates fields of type MERGEFIELD automatically with data from different data sources. In order to merge fields of type DOCVARIABLE, those fields need to be converted first:

TXTextControl.LoadSettings ls = new TXTextControl.LoadSettings();
ls.ApplicationFieldFormat = TXTextControl.ApplicationFieldFormat.MSWord;

textControl1.Load("template.docx",
        TXTextControl.StreamType.WordprocessingML, ls);

// loop through all fields in all text parts
foreach (IFormattedText textPart in textControl1.TextParts)
{
        foreach (ApplicationField appField in textPart.ApplicationFields)
        {
                // convert all "DocVariable" fields to "MergeFields"
                if (appField.TypeName == "DOCVARIABLE")
                {
                        MergeField newField = new MergeField();
                        newField.Name = appField.Parameters[0];

                        appField.Parameters = newField.ApplicationField.Parameters;
                        appField.TypeName = "MERGEFIELD";
                        appField.Text = newField.Name;
                }
        }
}

All ApplicationFields of type DOCVARIABLE are converted to fields of type MERGEFIELD by changing the TypeName property of the ApplicationField instance. The Parameters are copied by using a FieldAdapater for the type MERGEFIELD. This helps to keep the format consistent and compatible to MS Word.

At the end, the text of the field is set to the name of the field, as DOCVARIABLES have no visible text in MS Word.

Download the sample from GitHub and test it on your own.

GitHub

Download and Fork This Sample on GitHub

We proudly host our sample code on github.com/TextControl.

Please fork and contribute.

Requirements for This Sample

  • Visual Studio 2012 or better
  • TX Text Control .NET for Windows Forms (trial sufficient)