Manage Fields
- 7 minutes to read
A field is a placeholder for data that the document calculates (for example, the current date, a document property, a calculation result, or a value from a data source). The Word Processing Document API stores fields as Field objects.
A field consists of the following parts:
| Property | Description |
|---|---|
| Code | Gets the field code. |
| Result | Gets the field result. |
Field code contains the field type and field switches (for example, DATE \@ "MMMM d, yyyy"). Field result contains the content that the document displays. Code and Result properties get FieldFragment objects. A field fragment can contain text fragments, nested fields, other inline elements, paragraphs, and tables.
Insert a Field
Field is an inline element. To insert a field into a paragraph, add a Field object to the Paragraph.InlineElements collection.
To create a field with a text code, pass the code to the Field(code) constructor. To create a field code that contains nested fields, create a Field object with the parameterless constructor and add text fragments and nested fields to the Field.Code fragment.
The API does not calculate a field result when you insert a field. A new field has an empty result until you update the field.
The following code snippet inserts DATE and IF fields into a document, updates the fields, and displays field results in the console. The IF field code contains a nested formula field:
using System;
using DevExpress.Docs.Word;
using var document = new WordDocument();
// Insert a DATE field with a date format switch.
var dateParagraph = document.Body.AddParagraph("Report date: ");
var dateField = new Field(@"DATE \@ ""MMMM d, yyyy""");
dateParagraph.InlineElements.Add(dateField);
// Insert an IF field with a nested formula field in the field code.
var statusParagraph = document.Body.AddParagraph("Status: ");
var ifField = new Field();
ifField.Code.Add(new TextFragment("IF "));
ifField.Code.Add(new Field("= 2 + 2"));
ifField.Code.Add(new TextFragment(@" = 4 ""Passed"" ""Failed"""));
statusParagraph.InlineElements.Add(ifField);
document.UpdateAllFields();
Console.WriteLine(dateField.Result.GetText());
Console.WriteLine(ifField.Result.GetText());
Update Fields
Call the following methods to update fields and calculate field results:
| Method | Description |
|---|---|
| WordDocument.UpdateAllFields() | Updates all fields in the document. |
| DocumentFragment.UpdateAllFields() | Updates all fields in the document fragment. |
| DocumentFragment.UpdateFields(fields) | Updates the specified fields in the document fragment. |
Each method has an overload that accepts a FieldUpdateOptions object. Use field update options to fill merge fields with data and calculate document variable values.
The API updates nested fields before the field that contains them. After an update, the Field.Result fragment contains new elements. Elements that you got from the field result before the update are no longer in the document.
To update all fields before PDF export, set the PdfExportOptions.UpdateFieldsBeforeExport property to true.
Lock Fields
Set the Field.Locked property to true to keep the current field result. Update methods do not modify results of locked fields.
The following code snippet inserts TIME and DATE fields into a document, locks the DATE field, and updates both fields in the document body. The locked DATE field keeps its result:
using System;
using DevExpress.Docs.Word;
using var document = new WordDocument();
var paragraph = document.Body.AddParagraph();
var timeField = new Field(@"TIME \@ ""HH:mm""");
paragraph.InlineElements.Add(timeField);
var dateField = new Field(@"DATE \@ ""yyyy-MM-dd""");
dateField.Locked = true;
dateField.Result.Add(new TextFragment("2026-01-01"));
paragraph.InlineElements.Add(dateField);
document.Body.UpdateFields(timeField, dateField);
Console.WriteLine(timeField.Result.GetText());
Console.WriteLine(dateField.Result.GetText());
Fill Merge Fields with Data
MERGEFIELD fields display values from a data source. To fill merge fields with data from a data source record, specify the following properties and pass the FieldUpdateOptions object to an update method:
| Property | Description |
|---|---|
| FieldUpdateOptions.DataSource | Gets or sets the data source for MERGEFIELD fields. |
| FieldUpdateOptions.DataMember | Gets or sets the data source member (for example, a table in a DataSet) for MERGEFIELD fields. |
| FieldUpdateOptions.ActiveRecordIndex | Gets or sets the index of the data source record for MERGEFIELD fields. |
An update fills merge fields in the current document with data from a single record. To generate documents for all data source records, perform a mail merge.
The following code snippet inserts MERGEFIELD fields into a document and fills the fields with data from the second data source record:
using System.Data;
using System.IO;
using DevExpress.Docs.Word;
var customers = new DataTable("Customers");
customers.Columns.Add("Name");
customers.Columns.Add("City");
customers.Rows.Add("Maria Anders", "Berlin");
customers.Rows.Add("Thomas Hardy", "London");
using var document = new WordDocument();
var paragraph = document.Body.AddParagraph("Customer: ");
paragraph.InlineElements.Add(new Field("MERGEFIELD Name"));
paragraph.AddText(", ");
paragraph.InlineElements.Add(new Field("MERGEFIELD City"));
// Fill merge fields with data from the second record.
var options = new FieldUpdateOptions {
DataSource = customers,
ActiveRecordIndex = 1
};
document.UpdateAllFields(options);
Directory.CreateDirectory("output");
using var stream = File.Create(Path.Combine("output", "Document.docx"));
document.Save(stream, DocumentFormat.Docx);
Calculate DOCVARIABLE Field Values
A DOCVARIABLE field displays the value of a document variable. To calculate document variable values in code, implement the IDocumentVariableProvider interface and assign the provider to the FieldUpdateOptions.DocumentVariableProvider property.
When you update fields, the API calls the IDocumentVariableProvider.GetValue(variableName, arguments) method for each DOCVARIABLE field. The method returns a DocumentVariableValue object that contains text or another document. If the value contains a document, the API inserts the document content (including formatting, images, and hyperlinks) into the field result.
Use the following DocumentVariableValue properties to specify how the API inserts the value:
| Property | Description |
|---|---|
| DocumentVariableValue.KeepLastParagraph | Gets or sets whether to keep the last paragraph of the inserted document as a separate paragraph. |
| DocumentVariableValue.PreserveInsertedContentFormatting | Gets or sets whether to keep paragraph formatting of the first paragraph in the inserted document. |
| DocumentVariableValue.FieldLocked | Gets or sets whether to lock the DOCVARIABLE field after the API inserts the value. |
The following code snippet implements a document variable provider that calculates values of DOCVARIABLE fields. The provider returns text for the Greeting variable and inserts the content of another document for the Signature variable:
using System.Collections.Generic;
using System.IO;
using DevExpress.Docs.Word;
using var document = new WordDocument();
var paragraph = document.Body.AddParagraph();
paragraph.InlineElements.Add(new Field(@"DOCVARIABLE Greeting ""John Smith"""));
document.Body.AddParagraph().InlineElements.Add(new Field("DOCVARIABLE Signature"));
var options = new FieldUpdateOptions {
DocumentVariableProvider = new VariableProvider()
};
document.UpdateAllFields(options);
Directory.CreateDirectory("output");
using var stream = File.Create(Path.Combine("output", "Document.docx"));
document.Save(stream, DocumentFormat.Docx);
class VariableProvider : IDocumentVariableProvider {
public DocumentVariableValue GetValue(string variableName, IList<string> arguments) {
if (variableName == "Greeting" && arguments.Count > 0)
return new DocumentVariableValue($"Dear {arguments[0]},");
if (variableName == "Signature") {
var signature = new WordDocument();
signature.Body.AddParagraph("Best regards,");
signature.Body.AddParagraph("DevExpress Team");
return new DocumentVariableValue(signature) { KeepLastParagraph = true };
}
// Do not calculate values of other variables.
return null;
}
}