Skip to main content
A newer version of this page is available. .

How to: Insert and Modify Fields

  • 3 minutes to read

The following example illustrates how to add and modify fields manually.

All the fields in the document are contained in the FieldCollection, accessible through the SubDocument.Fields property.

Insert a Field

Use the FieldCollection.Create method to create a field, as illustrated below.

Document document = server.Document;
document.BeginUpdate();
document.Fields.Create(document.Range.Start, "DATE");
document.Fields.Update();
document.EndUpdate();

Pass the range to the FieldCollection.Create method to convert it to a field.

Document document = server.Document;
document.BeginUpdate();
document.AppendText("SYMBOL 0x54 \\f Wingdings \\s 24");
document.EndUpdate();
document.Fields.Create(document.Paragraphs[0].Range);
document.Fields.Update();

Modify Field Code

Use the SubDocument.BeginUpdate - SubDocument.EndUpdate paired methods to enable modifying field content.

Call the SubDocument.InsertText method to insert a format switch. Use the end position of the field code range as a method argument.

Call the Field.Update method to update the field result.

Document document = server.Document;
document.BeginUpdate();
document.Fields.Create(document.CaretPosition, "DATE");
document.EndUpdate();
for (int i = 0; i < document.Fields.Count; i++)
{
    string fieldCode = document.GetText(document.Fields[i].CodeRange);
    if (fieldCode == "DATE")
    {
        DocumentPosition position = document.Fields[i].CodeRange.End;
        document.InsertText(position, @" \@ ""M / d / yyyy HH: mm:ss""");
    }
}
document.Fields.Update();

Use the Field.ShowCodes property to change the target field’s display mode.

This code snippet displays field codes for all fields in the main document body.

The fields containing in the header or footer belong to a different FieldCollection. Use the Section.BeginUpdateHeader- Section.EndUpdateHeader or Section.BeginUpdateFooter - Section.EndUpdateFooter paired methods to retrieve the header or footer document.

Document document = server.Document;
document.LoadDocument("MailMergeSimple.docx", DocumentFormat.OpenXml);
for (int i = 0; i < document.Fields.Count; i++)
{
    document.Fields[i].ShowCodes = true;
}

Note

The header, footer, text box and comment in the word processing document do not belong to the main document body. Use the Section.BeginUpdateHeader - Section.EndUpdateHeader or Section.BeginUpdateFooter - Section.EndUpdateFooter paired methods to obtain the header or footer. Refer to the How to: Create and Modify Header topic for details. The TextBox.Document property allows you to retrieve the text box content and update the corresponding fields.

See Also