[]
        
(Showing Draft Content)

Update Fields

DsWord allows you to update the results of supported fields in the document using UpdateFields and Update methods. UpdateFields method of GcWordDocument and RangeBase classes enables you to update all supported fields in the document or all fields that support updating in the range. Meanwhile, Update method of ComplexField and SimpleField classes allows you to update the supported field results. See Field Type Options for more information.

Refer to the following example code to add TOC fields and hide the page number for the 'Heading 1' TOC entry:

// Initialize GcWordDocument.
GcWordDocument doc = new GcWordDocument();
            
// Create TOC field options.
TocFieldOptions options = new TocFieldOptions(doc);

// Build TOC with paragraphs.
foreach (TocStyleLevel style in options.Styles)
{
    switch (style.Level)
    {
        case OutlineLevel.Level1:
        case OutlineLevel.Level2:
        case OutlineLevel.Level3:
            style.Collect = true;
            break;
        default:
            style.Collect = false;
            break;
    }
}
            
// Add TOC field.
ComplexField field = doc.Body.AddParagraph().AddComplexField(options);

// Add a paragraph with Heading 1 style.
doc.Body.AddParagraph("Heading 1", doc.Styles[BuiltInStyleId.Heading1]);

// Add normal text for the heading and create next section.
doc.Body.AddParagraph("Document Solutions").AddSectionBreak();

// Add a paragraph with Heading 2 style.
doc.Body.AddParagraph("Heading 2", doc.Styles[BuiltInStyleId.Heading2]);

// Add normal text for the heading and create next section.
doc.Body.AddParagraph("Document Solutions for Word").AddSectionBreak();

// Add a paragraph with Heading 3 style.
doc.Body.AddParagraph("Heading 3", doc.Styles[BuiltInStyleId.Heading3]);
            
// Add normal text for the heading.
doc.Body.AddParagraph("DsWord");

// Update the field.
field.Update();

            
// Get first TOC field.
field = doc.Body.ComplexFields.First;
            
// Parse field options.
options = new TocFieldOptions(field);
            
// Hide page numbers for the first level TOC entries.
options.PageNumbers.OmitLevels.Set(OutlineLevel.Level1, OutlineLevel.Level1);
            
// Change TOC field instructions.
options.Save(field);
            
// Update all document fields.
doc.UpdateFields();

// Save the document.
doc.Save("TOC.docx");

Field Type Options

DsWord supports strong-typed access to the options of specific field types to read and write arguments and switches using PageFieldOptions, PageRefFieldOptions, SectionFieldOptions, SectionPagesFieldOptions, SeqFieldOptions, TcFieldOptions, TocFieldOptions, IndexFieldOptions, and XeFieldOptions classes.

PageFieldOptions, PageRefFieldOptions, SectionFieldOptions, SectionPagesFieldOptions, and SeqFieldOptions classes inherit FieldFormatOptions class that provides options to format the field result. The following table lists the options available in FieldFormatOptions class:

Options

Description

Load method

Loads options from a simple field or a complex field.

Save method

Saves options to a simple field or a complex field.

NumberFormat property

This property gets or sets the number format.

NumberStyle property

This property gets or sets the number formatting style.

StringStyle property

This property gets or sets the string formatting style.

ResultFormat property

This property gets or sets the result formatting rule.

Furthermore, DsWord also provides Add, AddComplexField, and Insert overload methods that accept IFieldOptions to add or insert specific types of fields. Refer to the following sections for more information and to add the supported fields:

PAGE Field Options

PAGE field inserts the page number on which it is present. Refer to the following example code to add PAGE field and specify its options:

// Initialize GcWordDocument.
var doc = new GcWordDocument();

// Set PAGE field for the page header.
var pgOptHeader = new PageFieldOptions(doc);
pgOptHeader.NumberStyle = NumberStyle.Decimal;

// Set PAGE field for page numbers in the body.
var pgOptBody = new PageFieldOptions(doc);
pgOptBody.NumberStyle = NumberStyle.UpperRoman;

// Add page header that includes the page number.
doc.Body.Sections.First.Headers[HeaderFooterType.Primary].Body.AddParagraph("Page Header - Page ").AddComplexField(pgOptHeader);

// Set style for page numbers in the document body.
var pageStyle = doc.Styles[BuiltInStyleId.IndexHeading];

// Add pages with periodic inclusions of the PAGE field.
var rnd = Util.NewRandom();
for (int i = 0; i < rnd.Next(6, 12); i++)
{
    var p = doc.Body.AddParagraph("This text is on page ", pageStyle).AddComplexField(pgOptBody);
    p.GetRange().Runs.Add(".");
    var par = Util.LoremIpsumPar();
    doc.Body.AddParagraph(par);
}

// Update fields using specific culture.
doc.UpdateFields(new GrapeCity.Documents.Word.Layout.WordLayoutSettings() { FontCollection = Util.FontCollection, Culture = CultureInfo.GetCultureInfo("en-US") });
            
// Save the document.
doc.Save("PageFieldOptions.docx");

PAGEREF Field Options

PAGEREF field inserts the page number of a bookmark for a cross-reference. PageRefFieldOptions class provides the following options along with the options inherited from FieldFormatOptions class:

Option

Description

Bookmark

Sets the bookmark name for a cross-reference.

Hyperlink

Indicates whether to create a hyperlink to the bookmarked paragraph.

DisplayRelative

Indicates whether to display the position relative to the source bookmark.

Refer to the following example code to add PAGEREF field and specify its options:

// Initialize GcWordDocument.
var doc = new GcWordDocument();

// Set bookmark name.
const string bmkName = "bmk";

// Set PAGEREF field options.
var pgRefOpt = new PageRefFieldOptions(doc, bmkName);
pgRefOpt.NumberStyle = NumberStyle.UpperRoman;
pgRefOpt.Hyperlink = true;

// Add a page header that includes the page number.
var pgOptHeader = new PageFieldOptions(doc);
pgOptHeader.NumberStyle = NumberStyle.Decimal;
doc.Body.Sections.First.Headers[HeaderFooterType.Primary].Body.AddParagraph("Page Header - Page ").AddComplexField(pgOptHeader);

// Add a paragraph with the PAGEREF.
var p = doc.Body.AddParagraph("Go to page ", doc.Styles[BuiltInStyleId.IndexHeading]).AddComplexField(pgRefOpt);
p.GetRange().Runs.Add("...");

// Add content.
var rnd = Util.NewRandom();
for (int i = 0; i < rnd.Next(20, 25); i++)
{
    doc.Body.AddParagraph(Util.LoremIpsumPar());
}

// End with the bookmarked paragraph.
doc.Body.AddParagraph("The End.").GetRange().Bookmarks.Add(bmkName);

// Update fields using specific culture.
doc.UpdateFields(new GrapeCity.Documents.Word.Layout.WordLayoutSettings() { FontCollection = Util.FontCollection, Culture = CultureInfo.GetCultureInfo("en-US") });
            
// Save the document.
doc.Save("PageRefFieldOptions.docx");

SECTION Field Options

SECTION field inserts the number of the current section. Refer to the following example code to add SECTION field and specify its options:

// Initialize GcWordDocument.
var doc = new GcWordDocument();

// Set PAGE field for the page header.
var pgOptHeader = new PageFieldOptions(doc);
pgOptHeader.NumberStyle = NumberStyle.Decimal;

// Set SECTION field for number of the section in the body.
var pgOptBody = new SectionFieldOptions(doc);
pgOptBody.NumberStyle = NumberStyle.UpperRoman;

// Add page header that includes the page number.
doc.Body.Sections.First.Headers[HeaderFooterType.Primary].Body.AddParagraph("Page Header - Page ").AddComplexField(pgOptHeader);

// Set style for page numbers in the document body.
var pageStyle = doc.Styles[BuiltInStyleId.IndexHeading];

// Add pages with periodic inclusions of the SECTION field.
var rnd = Util.NewRandom();
for (int i = 0; i < rnd.Next(6, 12); i++)
{
    var p = doc.Body.AddParagraph("Section ", pageStyle).AddComplexField(pgOptBody);
    var par = Util.LoremIpsumPar();
    doc.Body.AddParagraph(par);
    doc.Body.Paragraphs.Add().AddSectionBreak();
}

// Update fields using specific culture.
doc.UpdateFields(new GrapeCity.Documents.Word.Layout.WordLayoutSettings() { FontCollection = Util.FontCollection, Culture = CultureInfo.GetCultureInfo("en-US") });

// Save the document.
doc.Save("SectionFieldOptions.docx");

SECTIONPAGES Field Options

SECTIONPAGES field inserts the total number of pages in a section. Refer to the following example code to add SECTIONPAGES field and specify its options:

// Initialize GcWordDocument.
var doc = new GcWordDocument();

// Set PAGE field for the page header.
var pgOptHeader = new PageFieldOptions(doc);
pgOptHeader.NumberStyle = NumberStyle.Decimal;

// Set SECTIONPAGES field for page number in the body.
var pgOptBody = new SectionPagesFieldOptions(doc);
pgOptBody.NumberStyle = NumberStyle.UpperRoman;

// Add page header that includes the page number.
doc.Body.Sections.First.Headers[HeaderFooterType.Primary].Body.AddParagraph("Page Header - Page ").AddComplexField(pgOptHeader);

// Set style for page numbers in the document body.
var pageStyle = doc.Styles[BuiltInStyleId.IndexHeading];

// Add SECTIONPAGES field.
var p = doc.Body.AddParagraph("This text of this section is present on ", pageStyle).AddComplexField(pgOptBody);
p.GetRange().Runs.Add(" pages.");

// Add pages with content.
var rnd = Util.NewRandom();
for (int i = 0; i < rnd.Next(6, 12); i++)
{
    var par = Util.LoremIpsumPar();
    doc.Body.AddParagraph(par);   
}

// Update fields using specific culture.
doc.UpdateFields(new GrapeCity.Documents.Word.Layout.WordLayoutSettings() { FontCollection = Util.FontCollection, Culture = CultureInfo.GetCultureInfo("en-US") });

// Save the document.
doc.Save("SectionPagesFieldOptions.docx");

SEQ Field Options

SEQ field numbers the chapters, tables, figures, and other items in a document sequentially. SeqFieldOptions class provides the following options along with the options inherited from FieldFormatOptions class:

Option

Description

Id

Sets the name assigned to the series of items that are to be numbered.

Bookmark

Sets the bookmark name that refers to an item elsewhere in the document rather than in the current location.

Behavior

Sets the field behavior.

ResetTo

Sets the value to reset the sequence if Behavior property is ResetTo.

ResetAt

Sets the built-in heading style OutlineLevel at which to reset the sequence if Behavior property is ResetAt.

Hidden

Indicates whether to hide the field result.

Refer to the following example code to add SEQ field and specify its options:

// Initialize GcWordDocument.
var doc = new GcWordDocument();

// Set SEQ field ID.
string id = "ID";

// Set SEQ field for sequence in the body.
var pgOptBody = new SeqFieldOptions(doc, id);

// Start sequence with 5.
pgOptBody.Behavior = SeqFieldBehavior.ResetTo;
pgOptBody.ResetTo = 5;

// Set number style to upper roman.
pgOptBody.NumberStyle = NumberStyle.UpperRoman;

// Set style for page numbers in the document body.
var pageStyle = doc.Styles[BuiltInStyleId.IndexHeading];

// Add pages with periodic inclusions of the SECTION field.
var rnd = Util.NewRandom();
for (int i = 0; i < rnd.Next(6, 12); i++)
{
    var p = doc.Body.AddParagraph("Section ", pageStyle).AddComplexField(pgOptBody);
    var par = Util.LoremIpsumPar();
    doc.Body.AddParagraph(par);
    doc.Body.Paragraphs.Add().AddSectionBreak();
}

// Set behavior for the second SEQ field.
pgOptBody.Behavior = SeqFieldBehavior.Next;

// Set number style to decimal.
pgOptBody.NumberStyle = NumberStyle.Decimal;

// Add content to the section.
var p1 = doc.Body.AddParagraph("Section ", pageStyle).AddComplexField(pgOptBody);
var par1 = Util.LoremIpsumPar();
doc.Body.AddParagraph(par1);
doc.Body.Paragraphs.Add().AddSectionBreak();

// Update fields using specific culture.
doc.UpdateFields(new GrapeCity.Documents.Word.Layout.WordLayoutSettings() { FontCollection = Util.FontCollection, Culture = CultureInfo.GetCultureInfo("en-US") });

// Save the document.
doc.Save("SEQFieldOptions.docx");

TC Field Options

TC field specifies the text and page numbers for entries in a table of contents and in lists of tables, figures, and similar contents. TcFieldOptions class provides the following options:

Option

Description

Load

Loads options from a simple field or complex field.

Save

Saves options to a simple field or complex field.

Content

Gets the TOC item content.

Type

Sets the type of entry collected in a particular contents list.

DisplayLevel

Sets the level to display entry in a TOC field result.

OmitPageNumber

Sets whether to omit the page number for the entry in a TOC field result.

Refer to the following example code to add TC field and specify its options:

// Initialize GcWordDocument.
var doc = new GcWordDocument();

// Add page header.
var pgOptHeader = new PageFieldOptions(doc);
pgOptHeader.NumberStyle = NumberStyle.Decimal;
var pgOptBody = new PageFieldOptions(doc);
doc.Body.Sections.First.Headers[HeaderFooterType.Primary].Body.AddParagraph("Page Header - Page ").AddComplexField(pgOptHeader);

// Set TOC field options.
var tocOpts = new TocFieldOptions(doc);
tocOpts.TcFields.Collect = true;

// Add TOC and a section break to the document.
var toc = doc.Body.Paragraphs.Add().AddComplexField(tocOpts);
doc.Body.Paragraphs.Last().AddSectionBreak();

// Create TC field options.
TcFieldOptions tcOptions = new TcFieldOptions(doc);

// Create random content with three headers.
var rnd = Util.NewRandom();
for (int i = 0; i < rnd.Next(2, 4); i++)
{
    // Set content for TOC.
    tcOptions.Content.Text = $"First Header {i + 1}";
    tcOptions.DisplayLevel = OutlineLevel.Level1;
    var p = doc.Body.AddParagraph().AddComplexField(tcOptions);
    var par = Util.LoremIpsumPar();
    doc.Body.AddParagraph(par);
    doc.Body.Paragraphs.Add().AddSectionBreak();
    for (int j = 0; j < rnd.Next(3, 5); j++)
    {
        // Set content for TOC.
        tcOptions.Content.Text = $"Second Header {j + 1}";
        tcOptions.DisplayLevel = OutlineLevel.Level2;
        p = doc.Body.AddParagraph().AddComplexField(tcOptions);
        par = Util.LoremIpsumPar();
        doc.Body.AddParagraph(par);
        doc.Body.Paragraphs.Add().AddSectionBreak();
        for (int k = 0; k < rnd.Next(2, 3); k++)
        {
            // Set content for TOC.
            tcOptions.Content.Text = $"Third Header {k + 1}";
            tcOptions.DisplayLevel = OutlineLevel.Level3;
            p = doc.Body.AddParagraph().AddComplexField(tcOptions);
            par = Util.LoremIpsumPar();
            doc.Body.AddParagraph(par);
        }
    }
}

// Update fields using a specific culture.
doc.UpdateFields(new GrapeCity.Documents.Word.Layout.WordLayoutSettings() { FontCollection = Util.FontCollection, Culture = CultureInfo.GetCultureInfo("en-US") });

// Save the document.
doc.Save("TCFieldOptions.docx");

TOC Field Options

TOC field creates a table of contents. TocFieldOptions class provides the following options:

Option

Description

Load

Loads options from a simple field or complex field.

Save

Saves options to a simple field or complex field.

Styles

Gets the collection of styles that paragraphs should be collected by the TOC field.

TcFields

Gets options to collect TC fields by the TOC field.

SeqFields

Gets options to collect SEQ fields paragraphs by the TOC field.

PageNumbers

Gets options to show page numbers in the TOC field result.

EntryFormatting

Gets options to format TOC entries in the TOC field result.

Bookmark

Sets the bookmark name that allows you to include entries only from the portion of the document marked by this bookmark.

FlatList

Sets whether all TOC entries should be on the same level.

Refer to the following example code to add TOC field and specify its options:

// Initialize GcWordDocument.
var doc = new GcWordDocument();

// Add page header.
var pgOptHeader = new PageFieldOptions(doc);
pgOptHeader.NumberStyle = NumberStyle.Decimal;
var pgOptBody = new PageFieldOptions(doc);

doc.Body.Sections.First.Headers[HeaderFooterType.Primary].Body.AddParagraph("Page Header - Page ").AddComplexField(pgOptHeader);

// Set TOC field options.
var tocOpts = new TocFieldOptions(doc);
tocOpts.EntryFormatting.CreateHyperlink = true;
            
// Build TOC with paragraphs that formatted only 'Heading 1' or 'Heading 2' or 'Heading 3' styles.
foreach (TocStyleLevel style in tocOpts.Styles)
{
    switch (style.Level)
    {
        case OutlineLevel.Level1:
        case OutlineLevel.Level2:
        case OutlineLevel.Level3:
            style.Collect = true;
            break;
        default:
            style.Collect = false;
            break;
    }
}

// Add TOC and a section break to the document.
var toc = doc.Body.Paragraphs.Add().AddComplexField(tocOpts);
doc.Body.Paragraphs.Last().AddSectionBreak();

// Create random content with 3 levels of headers.
var rnd = Util.NewRandom();
for (int i = 0; i < rnd.Next(2, 4); i++)
{
    var p = doc.Body.AddParagraph($"This is top-level header {i + 1}", doc.Styles[BuiltInStyleId.Heading1]);
    var par = Util.LoremIpsumPar();
    doc.Body.AddParagraph(par);
    for (int j = 0; j < rnd.Next(3, 5); j++)
    {
        p = doc.Body.AddParagraph($"This is second-level header {j + 1}", doc.Styles[BuiltInStyleId.Heading2]);
        par = Util.LoremIpsumPar();
        doc.Body.AddParagraph(par);
        for (int k = 0; k < rnd.Next(2, 3); k++)
        {
            p = doc.Body.AddParagraph($"This is third-level header {k + 1}", doc.Styles[BuiltInStyleId.Heading3]);
            par = Util.LoremIpsumPar();
            doc.Body.AddParagraph(par);
        }
    }
}

// Update fields using a specific culture.
doc.UpdateFields(new GrapeCity.Documents.Word.Layout.WordLayoutSettings() { FontCollection = Util.FontCollection, Culture = CultureInfo.GetCultureInfo("en-US") });

// Save the document.
doc.Save("TOCFieldOptions.docx");

!type=note

Note: The example codes in this topic generate random text for the document using a helper file Util.cs. To run the example codes directly, download the file from here.

XE Field Options

XE field marks text for inclusion in an index. Word will automatically create the index based on the words or phrases you mark in the XE field. XeFieldOptions class provides the following options:

Option

Description

Entry

Gets the index entry.

Type

Sets the type of entry.

Bold

Sets whether to apply bold formatting to the entry's page number.

Italic

Sets whether to apply italic formatting to the entry's page number.

Behavior

Sets the field behavior.

PageRangeBookmark

Sets the name of the bookmark, which is used as the range of pages marked by the bookmark instead of the field page number.

Reference

Gets the formatted content, which is used in place of a page number.

Refer to the following example code to add XE field and specify its options:

// Initialize GcWordDocument.
GcWordDocument doc = new GcWordDocument();

// Create a paragraph for an index entry.
Paragraph p = doc.Body.AddParagraph();

// Create an index entry options.
XeFieldOptions xe = new XeFieldOptions(doc);
xe.Entry.Content.Text = "Zeus";

// Format page number for this entry with bold.
xe.Bold = true;

// Create the invisible index entry field with specified options.
p.AddComplexField(xe);

// Add visible text to the same paragraph.
p.AddRun("Zeus was recognized as the father of gods and humans.");

// Split document on several pages.
p.AddSectionBreak();

// Create a new paragraph for other index entries.
p = doc.Body.AddParagraph();

// Do not format page numbers for other index entries in bold.
xe.Bold = false;

// Create hierarchy index, so the entry is actually Zeus:Apollo
xe.Entry.AddSubEntry("Apollo");

// And create a new index entry field with specified options.
p.AddComplexField(xe);

// Change the index sub entry text, so the entry is actually Zeus:Artemis.
xe.Entry.SubEntry.Content.Text = "Artemis";

// Use a reference text instead of the index entry page number.
xe.Behavior = XeFieldBehavior.CrossReference;
xe.Reference.Text = "twin of Apollo";

// Create one more index entry field with specified options.
p.AddComplexField(xe);

// Add visible text for the index entries.
p.AddRun("Apollo and Artemis were siblings, twins actually, children of Zeus and Leto, a Titan goddess.");

// Create options for the index field.
IndexFieldOptions index = new IndexFieldOptions(doc);

// Align page numbers at the right side.
index.PageNumbers.Separator = "\t";

// Create index field with specified options.
ComplexField field = p.AddComplexField(index);

// Build the index.
field.Update();

// Save the Word document.
doc.Save("XEFieldOptions.docx");

INDEX Field Options

INDEX field creates an index, which is a list of terms or topics that are mentioned in a document. These are typically found at the end of the document for easy navigation. IndexFieldOptions class provides the following options:

Option

Description

Columns

Sets the number of columns per page.

Heading

Sets a heading text that appears at the start of each set of entries for any given letter.

FlatList

Sets whether subentries run into the same line as the main entry.

Culture

Sets the CultureInfo to sort index entries.

Bookmark

Sets the bookmark name that allows including entries only from the portion of the document marked by this bookmark.

EntriesType

Sets what type of XE fields to collect.

CharacterRange

Gets the range of characters that is used to include only those entries whose first letter is in the range.

PageNumbers

Gets options to show page numbers in the INDEX field result.

UseYomi

Sets whether to use IndexEntry.Yomi to sort index entries.

Refer to the following example code to add INDEX field and specify its options:

// Initialize GcWordDocument.
GcWordDocument doc = new GcWordDocument();

// Create a paragraph for an index entry.
Paragraph p = doc.Body.AddParagraph();

// Create an index entry options.
XeFieldOptions xe = new XeFieldOptions(doc);
xe.Entry.Content.Text = "Zeus";

// Create the invisible index entry field with specified options.
p.AddComplexField(xe);

// Add visible text to the same paragraph.
p.AddRun("Zeus was recognized as the father of gods and humans.");

// Split document on several pages.
p.AddSectionBreak();

// Create a new paragraph for other index entries.
p = doc.Body.AddParagraph();

// Change index entry text.
xe.Entry.Content.Text = "Apollo";

// Create a new index entry field with specified text.
p.AddComplexField(xe);

// Change index entry text.
xe.Entry.Content.Text = "Artemis";

// Create one more index entry field with specified text.
p.AddComplexField(xe);

// Add visible text for the index entries.
p.AddRun("Apollo and Artemis were siblings, twins actually, children of Zeus and Leto, a Titan goddess.");

// Create options for the index field.
IndexFieldOptions index = new IndexFieldOptions(doc);

// Layout index in two columns.
index.Columns = 2;

// Use headings for index entries.
index.Heading = "A";

// Align page numbers at right side.
index.PageNumbers.Separator = "\t";

// Create index field with specified options.
ComplexField field = p.AddComplexField(index);

// Build the index.
field.Update();

// Save the Word document.
doc.Save("IndexFieldOptions.docx");

Limitations

DsWord supports field type-specific options and updating fields only for the following field types:

  • PAGE

  • PAGEREF

  • SECTION

  • SECTIONPAGES

  • SEQ

  • TC

  • TOC

  • XE

  • INDEX