Back to Devexpress

Add, Manage, and Remove Fields with DevExpress Word Processing Document API

officefileapi-15280-word-processing-document-api-fields.md

latest29.4 KB
Original Source

Add, Manage, and Remove Fields with DevExpress Word Processing Document API

  • Jan 16, 2026
  • 13 minutes to read

A Field is a placeholder used to insert text and graphics into a document.

A field code includes the following elements:

ElementDescription
Field NameRefer to the following help topic for a list of all available fields: Field Codes.
PropertyInstruction or variable used in a field. This is an optional element.
SwitchAn optional parameter that allows you to modify a field result. A switch starts with a backslash followed by a switch argument. A field can have its own set of switches that specify the field’s behavior. You can also use format switches to define formats for numeric, text, date, and time fields. Refer to the following section for a list of supported format switches: Format Switches.

A field in the document consists of two ranges—CodeRange and ResultRange. Use the Field.Range property to obtain the total range that the field occupies.

Supported Field Types

Non-MailMergeRegular fields used to insert simple data (for example, DATE, TIME, or PAGE). The Non-MailMerge field results are shown after the update.MailMerge

Fields used in the mail merge process. You should bind a document to a data source to obtain merge field values. Execute mail merge to evaluate merge field values and display them in the document.

Check the Field.IsMergeField property to determine whether the field is a merge field. The merge field is a MergeField object.

MixedFields that do not require a data source to obtain their values (INCLUDEPICTURE, CREATEDATE, and DOCVARIABLE). They are replaced with the resulting values during mail merge.Formula

The = (Formula) field is a code that uses mathematical formulas and numeric field values to calculate a number. The formula field syntax is as follows:

{={NUMERIC FIELD} Operator {NUMERIC FIELD}}

The Word Processing Document API supports the following operators in the formula field:

  • Addition (+)
  • Subtraction (-)
  • Multiplication (*)
  • Division (/)
  • Powers and Roots (^)
  • Equal to (=)
  • Less than (<)
  • Less than or equal to (<=)
  • Greater than (>)
  • Greater than or equal to (>=)
  • Not equal to (<>)

You can change the field’s numeric format. Refer to the following topic for a list of available numeric format switches: Numeric Format Switch. Please note that the formula field does not work with layout-dependent fields (for example, PAGE or NUMPAGES) in headers or footers.

Insert Fields

Fields are stored in the field collection (FieldCollection). The SubDocument.Fields property allows you to access the field collection. Call the FieldCollection.Create method to insert a new field. You can add fields to any SubDocument – the main document body, headers, footers, text boxes, comments, footnotes, and endnotes. Use the following API to access the content of these document parts:

Document partMember
Main document bodySubDocument.BeginUpdateSubDocument.EndUpdate
HeaderSection.BeginUpdateHeaderSection.EndUpdateHeader
FooterSection.BeginUpdateFooterSection.EndUpdateFooter
CommentComment.BeginUpdateComment.EndUpdate
Footnote and EndnoteNote.BeginUpdateNote.EndUpdate
Text BoxTextBox.Document

Create a Field

The code snippet below uses the SYMBOL field to add a check mark (✔) to the document:

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

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

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

    // Create the "SYMBOL" field.
    document.Fields.Create(document.Range.Start, "SYMBOL 252 \\f Wingdings \\s 28");

    // 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.Docx);
}
vb
Imports DevExpress.XtraRichEdit
Imports DevExpress.XtraRichEdit.API.Native
'...

Using wordProcessor As New RichEditDocumentServer()
    ' Access a document.
    Dim document As Document = wordProcessor.Document

    ' Start to edit the document.
    document.BeginUpdate()

    ' Create the "SYMBOL" field.
    document.Fields.Create(document.Range.Start, "SYMBOL 252 \f Wingdings \s 28")

    ' 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.Docx)
End Using

Create a Field from a Range

The code sample below inserts text and converts it to the SYMBOL field.

View Example

csharp
using DevExpress.XtraRichEdit;
using DevExpress.XtraRichEdit.API.Native;

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

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

    // Append text.
    document.AppendText("SYMBOL 0x54 \\f Wingdings \\s 24");

    // Convert inserted text to a field.
    document.Fields.Create(document.Paragraphs[0].Range);

    // Update all fields.
    document.Fields.Update();

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

    // Save the result
    document.SaveDocument("Result.docx", DocumentFormat.Docx);
}
vb
Imports DevExpress.XtraRichEdit
Imports DevExpress.XtraRichEdit.API.Native

'...
Using wordProcessor As New RichEditDocumentServer()
    Dim document As Document = wordProcessor.Document

    ' Start to edit the document.
    document.BeginUpdate()

    ' Append text.
    document.AppendText("SYMBOL 0x54 \f Wingdings \s 24")

    ' Convert inserted text to a field.
    document.Fields.Create(document.Paragraphs(0).Range)

    ' Update all fields.
    document.Fields.Update()

    ' Finalize to edit the document.
    document.EndUpdate()

    ' Save the result
    document.SaveDocument("Result.docx", DocumentFormat.Docx)
End Using

Modify Fields

Call the SubDocument.GetText method and pass the field’s CodeRange or ResultRange as a parameter to retrieve the field code or value. Use the SubDocument.InsertText method to add text to a field code or a result.

Determine a Field Type and Modify a Field

The following code snippet specifies a custom date and time format for all DATE fields in the document:

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

using (RichEditDocumentServer wordProcessor = new RichEditDocumentServer())
{
    // Access a document.
    Document document = wordProcessor.Document;
    // ...
    // Check all fields in the document.
    for (int i = 0; i < document.Fields.Count; i++)
    {
        // Access a field code.
        string fieldCode = document.GetText(document.Fields[i].CodeRange);
        // Check whether a field code is "DATE".
        if (fieldCode == "DATE")
        {
            // Set the document position to the end of the field code range.
            DocumentPosition position = document.Fields[i].CodeRange.End;
            // Specify a date and time format for the field. 
            document.InsertText(position, @" \@ ""M/d/yyyy HH:mm:ss""");
        }
    }
    // Update all fields in the main document body.
    document.Fields.Update();
}
vb
Imports DevExpress.XtraRichEdit
Imports DevExpress.XtraRichEdit.API.Native
'...

Using wordProcessor As New RichEditDocumentServer()
    ' Access a document.
    Dim document As Document = wordProcessor.Document
    ' ...
    ' Check all fields in the document.
    For i As Integer = 0 To document.Fields.Count - 1
        ' Access a field code.
        Dim fieldCode As String = document.GetText(document.Fields(i).CodeRange)
        ' Check whether a field code is "DATE".
        If fieldCode = "DATE" Then
            ' Set the document position to the end of the field code range.
            Dim position As DocumentPosition = document.Fields(i).CodeRange.End
            ' Specify a date and time format for the field. 
            document.InsertText(position, " \@ ""M/d/yyyy HH:mm:ss""")
        End If
    Next i
    ' Update all fields in the main document body.
    document.Fields.Update()
End Using

Retrieve a Field Result

The code sample below checks all field results and inserts “Empty Value!” if the field result is empty:

csharp
using DevExpress.XtraRichEdit;
using DevExpress.XtraRichEdit.API.Native;
using System.Drawing;

using (var wordProcessor = new RichEditDocumentServer()) {
    Document document = wordProcessor.Document;
    foreach (Field field in document.Fields) {
        string strResult = document.GetText(field.ResultRange);

        if (strResult == "") {
            document.InsertText(field.ResultRange.Start, "Empty Value!");
        }
    }
}
vb
``Imports DevExpress.XtraRichEdit
Imports DevExpress.XtraRichEdit.API.Native
Imports System.Drawing

Using wordProcessor = New RichEditDocumentServer()
    Dim document As Document = wordProcessor.Document
    For Each field As Field In document.Fields
        Dim strResult As String = document.GetText(field.ResultRange)

        If strResult = "" Then
            document.InsertText(field.ResultRange.Start, "Empty Value!")
        End If
    Next field
End Using

Retrieve a Layout-Dependent Field Result

The following fields are layout-dependent:

If one of these fields is located outside the main document body (header/footer, endnote/footer, comment, or text box), use the Layout API to get the field result. Obtain the PlainTextBox related to the field and call the DocumentLayout.GetText(LayoutElement) method (or use the PlainTextBox.Text property) to retrieve the field result.

The following code sample retrieves the result of a field located in a shape:

csharp
using DevExpress.XtraRichEdit;
using DevExpress.XtraRichEdit.API.Layout;
using DevExpress.XtraRichEdit.API.Native;

using (var wordProcessor = new RichEditDocumentServer()) {
    // Load a document
    wordProcessor.LoadDocument("Document.docx");
    var document = wordProcessor.Document;

    // Obtain fields located in the shape
    var shape = document.Shapes[0];
    var shapeFields = document.Fields.Get(shape.Range);
    var numPagesField = shapeFields[0];

    // Obtain the field value
    var numPagesFieldBox = wordProcessor.DocumentLayout.GetElement<PlainTextBox>(numPagesField.ResultRange.Start);
    var numPagesFieldResult = formattedShape.Text;
}
vb
Imports DevExpress.XtraRichEdit
Imports DevExpress.XtraRichEdit.API.Layout
Imports DevExpress.XtraRichEdit.API.Native

Using wordProcessor As New RichEditDocumentServer()
    ' Load a document
    wordProcessor.LoadDocument("Document.docx")
    Dim document = wordProcessor.Document

    ' Obtain fields located in the shape
    Dim shape = document.Shapes(0)
    Dim shapeFields = document.Fields.Get(shape.Range)
    Dim numPagesField = shapeFields(0)

    ' Obtain the field value
    Dim numPagesFieldBox = wordProcessor.DocumentLayout.GetElement(Of PlainTextBox)(numPagesField.ResultRange.Start)
    Dim numPagesFieldResult = formattedShape.Text
End Using

Update Fields

Most fields are updated automatically when the document is saved or printed, or during the mail merge operation. Use the following methods to update document fields on demand:

MethodDescription
Field.UpdateUpdates a field.
FieldCollection.UpdateUpdates all fields in specific parts of the document (main body, text box, header, footer, comment, footnote, and endnote).
Document.UpdateAllFieldsUpdates all fields in the document.

The code sample below updates all fields in the document:

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

using (RichEditDocumentServer wordProcessor = new RichEditDocumentServer())
{
    // Access a document.
    Document document = wordProcessor.Document;
    //...
    // Update all fields in the document.
    document.UpdateAllFields();
}
vb
Imports DevExpress.XtraRichEdit
Imports DevExpress.XtraRichEdit.API.Native
'...

Using wordProcessor As New RichEditDocumentServer()
    ' Access a document.
    Dim document As Document = wordProcessor.Document
    '...
    ' Update all fields in the document.
    document.UpdateAllFields()
End Using

If the field’s Field.Locked property is true , this field is not updated. You can set the FieldOptions.UpdateLockedFields option to UpdateLockedFields.Always to update locked fields.

Update DOCVARIABLE Fields

Use the FieldOptions.UpdateDocVariablesBeforePrint and FieldOptions.UpdateDocVariablesBeforeCopy field options to specify whether to update the DOCVARIABLE field before the document is printed or before the field is copied. When the DOCVARIABLE field is updated, the RichEditDocumentServer.CalculateDocumentVariable event fires. Handle this event to analyze DOCVARIABLE field switches and arguments, and specify how to calculate a field result.

The RichEditDocumentServer.CalculateDocumentVariable event does not occur for a locked DOCVARIABLE field, and the field value remains unchanged. Set the FieldOptions.UpdateLockedFields option to the UpdateLockedFields.DocVariableOnly value to update locked DOCVARIABLE fields.

Tip

Refer to the following GitHub examples for more information on how to use the DOCVARIABLE fields:

View Example: How to use document variable (DOCVARIABLE) fields

View Example: How to replace document fields with their values

Suppress Field Updates for Loaded Documents

The Word Processing Document API updates all document fields when it loads a document. You can cancel the DATE, TIME, and DOCVARIABLE field updates. Handle the RichEditDocumentServer.BeforeImport event and define the UpdateFieldOptions options within the event handler to specify whether to update these fields.

The following example demonstrates how to cancel the update of the DATE, TIME, and DOCVARIABLE document fields for all document formats:

csharp
using DevExpress.XtraRichEdit;
using DevExpress.XtraRichEdit.Import;
//...

using (RichEditDocumentServer wordProcessor = new RichEditDocumentServer())
{
    // Handle the BeforeImport event.
    wordProcessor.BeforeImport += WordProcessor_BeforeImport;

    // Load a document from the file.
    wordProcessor.LoadDocument("FirstLook.docx");
}

private static void WordProcessor_BeforeImport(object sender, BeforeImportEventArgs e)
{

    // Cancel the DATE, TIME, and DOCVARIABLE fields' update.
    UpdateFieldOptions updateFieldOptions = ((DocumentImporterOptions)e.Options).UpdateField;
    updateFieldOptions.Date = false;
    updateFieldOptions.Time = false;
    updateFieldOptions.DocVariable = false;
}
vb
Imports DevExpress.XtraRichEdit
Imports DevExpress.XtraRichEdit.Import
'...

Using wordProcessor As New RichEditDocumentServer()

    ' Handle the BeforeImport event.
    AddHandler wordProcessor.BeforeImport, AddressOf WordProcessor_BeforeImport

    ' Load a document from the file.
    wordProcessor.LoadDocument("FirstLook.docx")
End Using

Private Shared Sub WordProcessor_BeforeImport(ByVal sender As Object, ByVal e As BeforeImportEventArgs)

    ' Cancel the DATE, TIME, and DOCVARIABLE fields' update.
    Dim updateFieldOptions As UpdateFieldOptions = CType(e.Options, DocumentImporterOptions).UpdateField
    updateFieldOptions.Date = False
    updateFieldOptions.Time = False
    updateFieldOptions.DocVariable = False
End Sub

Replace Fields with Field Values

You can unlink a field to convert the field result to text or graphics. Unlinked fields cannot be updated. Use the following methods to unlink document fields:

MethodDescription
Field.UnlinkReplaces the field with the field value.
FieldCollection.UnlinkReplaces all fields with their values in a specific document part (main body, header, footer, comment, text box, footnote, or endnote).
Document.UnlinkAllFieldsReplaces all document fields with field values.

The following example unlinks all fields in text boxes:

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

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

    // Check all shapes in the document.
    foreach (Shape shape in document.Shapes)
    {
        // Check whether the shape is a text box.
        if (shape.ShapeFormat.HasText)
        {
            // Access text box content.
            SubDocument textBoxDocument = shape.ShapeFormat.TextBox.Document;
            //...
            // Unlink all fields in the text box.
            textBoxDocument.Fields.Unlink();
        }
    }
}
vb
Imports DevExpress.XtraRichEdit
Imports DevExpress.XtraRichEdit.API.Native
'...

Using wordProcessor As New RichEditDocumentServer()
    ' Access a document.
    Dim document As Document = wordProcessor.Document

    ' Check all shapes in the document.
    For Each shape As Shape In document.Shapes

        ' Check whether the shape is a text box.
        If shape.ShapeFormat.HasText Then

            ' Access text box content.
            Dim textBoxDocument As SubDocument = shape.ShapeFormat.TextBox.Document
            '...
            ' Unlink all fields in the text box.
            textBoxDocument.Fields.Unlink()
        End If
    Next shape
End Using

Show Field Codes

Use the Field.ShowCodes property to display field codes for specific fields instead of field results.

The code snippet below displays field codes for all fields in the main document body:

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

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

    // Load a document from the file.
    document.LoadDocument("MailMergeSimple.docx", DocumentFormat.Docx);

    // Check all fields in the main document body.
    for (int i = 0; i < document.Fields.Count; i++)
    {
        // Show field codes.
        document.Fields[i].ShowCodes = true;
    }
}
vb
Imports DevExpress.XtraRichEdit
Imports DevExpress.XtraRichEdit.API.Native
'...

Using wordProcessor As New RichEditDocumentServer()
    ' Access a document.
    Dim document As Document = wordProcessor.Document

    ' Load a document from the file.
    document.LoadDocument("MailMergeSimple.docx", DocumentFormat.Docx)

    ' Check all fields in the main document body.
    For i As Integer = 0 To document.Fields.Count - 1
        ' Show field codes.
        document.Fields(i).ShowCodes = True
    Next i
End Using

Specify Field Options

Use the RichEditDocumentServer.Options.Fields property to specify field options. These options define the appearance and behavior of the document fields.

The code snippet below demonstrates how to specify field options.

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

using (RichEditDocumentServer wordProcessor = new RichEditDocumentServer())
{
    // Specify field options.
    FieldOptions fieldOptions = wordProcessor.Options.Fields;
    fieldOptions.HighlightMode = FieldsHighlightMode.Always;
    fieldOptions.HighlightColor = System.Drawing.Color.LightSalmon;
    fieldOptions.UseCurrentCultureDateTimeFormat = true;
    fieldOptions.ThrowExceptionOnInvalidFormatSwitch = true;
    fieldOptions.UpdateFieldsInTextBoxes = true;

    // Access a document.
    Document document = wordProcessor.Document;

    // Insert a text box in the document.
    Shape myTextBox = document.Shapes.InsertTextBox(document.Range.Start);

    // Access text box content.
    SubDocument textBoxDocument1 = myTextBox.ShapeFormat.TextBox.Document;

    // Create the "DATE" field.
    textBoxDocument.Fields.Create(textBoxDocument.Range.Start, "DATE");

    // Update the field.
    textBoxDocument.Fields.Update();
}
vb
Imports DevExpress.XtraRichEdit
Imports DevExpress.XtraRichEdit.API.Native
'...

Using wordProcessor As New RichEditDocumentServer()
    ' Specify field options.
    Dim fieldOptions As FieldOptions = wordProcessor.Options.Fields
    fieldOptions.HighlightMode = FieldsHighlightMode.Always
    fieldOptions.HighlightColor = System.Drawing.Color.LightSalmon
    fieldOptions.UseCurrentCultureDateTimeFormat = True
    fieldOptions.ThrowExceptionOnInvalidFormatSwitch = True
    fieldOptions.UpdateFieldsInTextBoxes = True

    ' Access a document.
    Dim document As Document = wordProcessor.Document

    ' Insert a text box in the document.
    Dim myTextBox As Shape = document.Shapes.InsertTextBox(document.Range.Start)

    ' Access text box content.
    Dim textBoxDocument1 As SubDocument = myTextBox.ShapeFormat.TextBox.Document

    ' Create the "DATE" field.
    textBoxDocument.Fields.Create(textBoxDocument.Range.Start, "DATE")

    ' Update the field.
    textBoxDocument.Fields.Update()
End Using

Remove Fields

Call the SubDocument.Delete method and pass the field range to remove the field from the document.

The following example removes all fields from the document:

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

using (RichEditDocumentServer wordProcessor = new RichEditDocumentServer())
{
    // Access a document.
    Document document = wordProcessor.Document;
    //...
    // Remove all fields from the collection
    for (int i = document.Fields.Count-1; i >= 0; i--) 
    {
        document.Delete(document.Fields[i].Range); 
    }
}
vb
Imports DevExpress.XtraRichEdit
Imports DevExpress.XtraRichEdit.API.Native
'...

Using wordProcessor As New RichEditDocumentServer()
    ' Access a document.
    Dim document As Document = wordProcessor.Document
    '...
    ' Remove all fields from the collection
    For i As Integer = document.Fields.Count-1 To 0 Step -1
      document.Delete(document.Fields(i).Range)
    Next i
End Using

To delete a nested field, set the parent field’s ShowCodes property to true before the Delete method call. Use the Field.Parent property to access the parent field.

See Also

Field Codes

Format Switches