Skip to main content
All docs
V21.2

How to: Create a Nested Field

  • 3 minutes to read

The RichEditDocumentServer allows you to nest one field inside another field that requires input (for example, the IF or DOCVARIABLE fields) so that the nested field result affects the parent field result. You can add a parent field to any part of a document (the main document body, headers, footers, text boxes, comments, footnotes, and endnotes) and use any nested field code inside a parent field.

Note

Do not nest the PAGE and NUMPAGES fields inside fields that are in headers or footers. Field values can be incorrect due to limitations of the current layout calculation.

To insert a nested field, create a parent field with a placeholder for a nested field. Then, find the placeholder text and replace it with the nested field code in the code range of the parent field.

The following code sample nests the MERGEFIELD field inside the IF field. The resulting field code specifies that if the customer order is greater than or equal to 100 units, the result is “Thanks”; but if the customer order is fewer than 100 units, the result is “The minimum order is 100 units”.

Create a Nested Field

using DevExpress.XtraRichEdit;
using DevExpress.XtraRichEdit.API.Native;
//...

var bindingSource = new BindingSource();
bindingSource.DataSource = new
{
    Order = 10,
    Amount = 12345.678m,
};

using (RichEditDocumentServer wordProcessor = new RichEditDocumentServer())
{
    // Access a document.
    Document document = wordProcessor.Document;

    // Specify the data source of the document.
    wordProcessor.Options.MailMerge.DataSource = bindingSource;

    // Start to edit the document.
    document.BeginUpdate();

    // Create the "IF" field.
    Field field = document.Fields.Create(document.Range.Start, @"IF { placeholder } > 100 ""Thanks"" ""The minimum order is 100 units""");

    // Search for the placeholder text.
    DocumentRange nestedFieldRange = document.FindAll("{ placeholder }", SearchOptions.WholeWord, field.CodeRange).First();

    // Delete the placeholder text.
    document.Delete(nestedFieldRange);

    // Insert the MERGEFIELD field nested in the IF field.
    document.Fields.Create(nestedFieldRange.Start, "MERGEFIELD Order");

    // Finalize to edit the document.
    document.EndUpdate();

    // Update all fields in the main document body.
    document.Fields.Update();

    // ...

    // Save the document to the file.
    document.SaveDocument("Result.docx", DocumentFormat.OpenXml);
}