Create Fields in Word documents using C# and VB.NET

Field elements in Word documents are dynamic elements, placeholders for dynamic data, or changing aspects of the document. For instance, a field can be a page reference, property reference, or date and time value.

With the GemBox.Document library you can create fields in your Word files programmatically in C# and VB.NET.

You can define fields with the Field.FieldType class and optionally with Field.InstructionInlines, which may contain additional field arguments and switches, or even other nested fields. The field's instructions (the field's code) define how Field.ResultInlines (the field's value) should be updated or calculated.

The following example shows how to create fields of different types with various arguments and switches.

Word document with fields result value and instruction code
Screenshot of toggled field code and result in Word file
using GemBox.Document;

class Program
{
    static void Main()
    {
        // If using the Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY");

        var document = new DocumentModel();

        var section = new Section(document);
        document.Sections.Add(section);

        // Add '{ AUTHOR }' field.
        section.Blocks.Add(
            new Paragraph(document,
                new Run(document, "Author: "),
                new Field(document, FieldType.Author, null, "Mario at GemBox")));

        // Add '{ DATE }' field.
        section.Blocks.Add(
            new Paragraph(document,
                new Run(document, "Date: "),
                new Field(document, FieldType.Date)));

        // Add '{ DATE \@ "dddd, MMMM dd, yyyy" }' field.
        section.Blocks.Add(
            new Paragraph(document,
                new Run(document, "Date with specified format: "),
                new Field(document, FieldType.Date, "\\@ \"dddd, MMMM dd, yyyy\"")));

        document.Save("Fields.%OutputFileType%");
    }
}
Imports GemBox.Document

Module Program

    Sub Main()

        ' If using the Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY")

        Dim document As New DocumentModel()

        Dim section As New Section(document)
        document.Sections.Add(section)

        ' Add '{ AUTHOR }' field.
        section.Blocks.Add(
            New Paragraph(document,
                New Run(document, "Author: "),
                New Field(document, FieldType.Author, Nothing, "Mario at GemBox")))

        ' Add '{ DATE }' field.
        section.Blocks.Add(
            New Paragraph(document,
                New Run(document, "Date: "),
                New Field(document, FieldType.Date)))

        ' Add '{ DATE \@ "dddd, MMMM dd, yyyy" }' field.
        section.Blocks.Add(
            New Paragraph(document,
                New Run(document, "Date with specified format: "),
                New Field(document, FieldType.Date, "\@ ""dddd, MMMM dd, yyyy""")))

        document.Save("Fields.%OutputFileType%")

    End Sub
End Module

Updating fields

It is possible to update fields in runtime to check their result values. This is useful for validating the field and its result before saving the current content as a file.

You can check our documentation for more information about this process, including a list of which field types you can update with the Update method.

The example below shows how to resolve a field value and access it.

Resulting Word file containing two resolved fields
Resulting Word file containing two resolved fields
using GemBox.Document;
using System.Linq;

class Program
{
    static void Main()
    {
        // If using the Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY");

        var document = new DocumentModel();

        var section = new Section(document);
        document.Sections.Add(section);

        // A simple '{ IF }' field, that will result on different texts if true or false.
        var simpleField = new Field(document, FieldType.If, "10 = 10 \"The result is true.\" \"The result is false.\"");

        // A complex '{ IF }' field, that will result on texts with different formats if true or false.
        var complexField = new Field(document, FieldType.If,
            new Run(document, "10 = 10 "),
            new Run(document, "\"The result is true.\"") { CharacterFormat = { FontColor = Color.Green, Bold = true } },
            new Run(document, "\"The result is false.\"") { CharacterFormat = { FontColor = Color.Red, Italic = true } });

        // Add both fields to the document.
        section.Blocks.Add(new Paragraph(document, simpleField));
        section.Blocks.Add(new Paragraph(document, complexField));

        // Call Update method to resolve the field's value.
        simpleField.Update();
        complexField.Update();

        // Get the result, which for simpleField will be a simple Run with "The result is true." as text.
        Run simpleResult = simpleField.ResultInlines.First() as Run;

        // Get the result, which will be a Run with FontColor Green and Bold set to true.
        Run complexResult = complexField.ResultInlines.First() as Run;

        document.Save("FieldsUpdated.%OutputFileType%");
    }
}
Imports GemBox.Document
Imports System.Linq

Module Program

    Sub Main()

        ' If using the Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY")

        Dim document = New DocumentModel()

        Dim section = New Section(document)
        document.Sections.Add(section)

        ' A simple '{ IF }' field, that will result on different texts if true or false.
        Dim simpleField = New Field(document, FieldType.If, "10 = 10 ""The result Is True."" ""The result Is False.""")

        ' A complex '{ IF }' field, that will result on texts with different formats if true or false.
        Dim complexField = New Field(document, FieldType.If,
            New Run(document, "10 = 10 "),
            New Run(document, """The result Is True.""") With {.CharacterFormat = New CharacterFormat() With {.FontColor = Color.Green, .Bold = True}},
            New Run(document, """The result Is False.""") With {.CharacterFormat = New CharacterFormat() With {.FontColor = Color.Red, .Italic = True}})

        ' Add both fields to the document.
        section.Blocks.Add(New Paragraph(document, simpleField))
        section.Blocks.Add(New Paragraph(document, complexField))

        ' Call Update method to resolve the field's value.
        simpleField.Update()
        complexField.Update()

        ' Get the result, which for simpleField will be a simple Run with "The result is true." as text.
        Dim simpleResult = TryCast(simpleField.ResultInlines.First(), Run)

        ' Get the result, which will be a Run with FontColor Green And Bold set to true.
        Dim complexResult = TryCast(complexField.ResultInlines.First(), Run)

        document.Save("FieldsUpdated.%OutputFileType%")

    End Sub
End Module

On the following page, you can find a list of field codes supported by Microsoft Word. It also contains a description of each field, its syntax, and available switches.

By default, when viewing a Word document in the Microsoft Word application, the field's value is displayed, and the field's instructions are not visible. However, by pressing ALT + F9, you can toggle between the field's code and its result.

Interactive form fields are a particular type of Field elements that contain Field.FormData objects. With these types of fields you can create, read, and update fillable forms in your Word documents.

See also


Next steps

GemBox.Document is a .NET component that enables you to read, write, edit, convert, and print document files from your .NET applications using one simple API. How about testing it today?

Download Buy