Working with Fields

Working with Fields

A Word field – DATE, IF, DATABASE, REF, and dozens of others – is represented in Aspose.Words FOSS for .NET by the Field class and its subclasses, all in the Aspose.Words.Fields namespace. This page covers the core field engine: the Field object model itself, how fields are collected and updated, and the callback interfaces that let you plug in custom data and behavior during a field update. Specific field families – hyperlinks and cross-references, date/time fields, mail-merge fields, index and table-of-contents fields – each have their own dedicated developer-guide page.


The Field Object Model

Every field in a document is a Field instance made up of three marker nodes – FieldStart, Separator, and FieldEnd – exposed as the Field.Start, Field.Separator, and Field.End properties. Field.Type identifies which FieldType the field represents, Field.Result and Field.DisplayResult expose the last-calculated value, and Field.Format holds any switches (such as numeric or date-time format strings) attached to the field code. Field.IsLocked and Field.IsDirty report the field’s locked and stale state. Call Field.GetFieldCode() to read the raw field code text, Field.Update() to recalculate the result, Field.Unlink() to replace the field with static text, and Field.Remove() to delete it entirely.


Accessing and Updating Fields in a Document

Document.Range.Fields returns a FieldCollection – the fields contained in that range, with Count, Remove(), RemoveAt(), and Clear() for bulk removal. Range.UpdateFields() recalculates every field in the range, Range.UnlinkFields() converts every field in the range to static text, and Range.NormalizeFieldTypes() reconciles a field’s stored type code against its actual field code after manual edits. DocumentBuilder.InsertField() inserts a new field at the cursor, with overloads that either update the new field’s result immediately or leave it for a later Range.UpdateFields() pass.


Field Update Options and Culture

Document.FieldOptions is a FieldOptions instance that governs how the whole document’s fields behave when updated: CurrentUser supplies the UserInformation used by identity fields, DefaultDocumentAuthor seeds author-related results, LegacyNumberFormat and UseInvariantCultureNumberFormat control number formatting, and PreProcessCulture and FieldUpdateCultureSource (paired with the IFieldUpdateCultureProvider callback) determine which culture governs date and number formatting during an update. TemplateName, FileName, and BuiltInTemplatesPaths supply values that template- and file-name-aware fields read back.


Tracking and Customizing Field Updates

Implement IFieldUpdatingCallback (FieldUpdating and FieldUpdated) on FieldOptions to run code immediately before and after every field recalculates – useful for auditing which fields changed in a batch job. Implement IFieldUpdatingProgressCallback (Notify) to track overall progress across a large document; it receives a FieldUpdatingProgressArgs with TotalFieldsCount, UpdatedFieldsCount, and UpdateCompleted. To change how a field’s numeric or general result is rendered as text, implement IFieldResultFormatter (Format(value, format) and FormatNumeric(value, format)) and assign it to FieldOptions.ResultFormatter.


Supplying External Data to Fields

The DATABASE field reads its rows through IFieldDatabaseProvider.GetQueryResult(), which returns a FieldDatabaseDataTable (ColumnNames, Rows) built from FieldDatabaseDataRow (Values) instances – assign your implementation to FieldOptions.FieldDatabaseProvider. Comparison fields such as IF evaluate their condition through IComparisonExpressionEvaluator.Evaluate(), which receives a ComparisonExpression (LeftExpression, ComparisonOperator, RightExpression) and returns a ComparisonEvaluationResult (Result, ErrorMessage); assign a custom evaluator to FieldOptions.ComparisonExpressionEvaluator to override the default comparison logic. Fields that normally prompt the user for input during an update – such as ASK and FILLIN – call IFieldUserPromptRespondent.Respond() when one is assigned to FieldOptions.UserPromptRespondent, so an unattended update does not block waiting for interactive input.


User and Document Identity for Fields

UserInformation (Name, Initials, Address, and the static UserInformation.DefaultUser) supplies the identity that author- and user-name-related fields read from. Assign an instance to Document.FieldOptions.CurrentUser before updating fields that depend on document author or user identity.


Tips and Best Practices

  • Aspose.Words FOSS does not recalculate fields automatically on load or save the way Word does – call Range.UpdateFields() (or Field.Update() for a single field) explicitly after any programmatic edit that should be reflected in field results.
  • FieldStart, Separator, and FieldEnd are real nodes in the document tree; remove a field through Field.Remove() or Field.Unlink() rather than deleting the marker nodes directly, or the field structure can end up inconsistent.
  • Fields whose result depends on page layout – PAGE, NUMPAGES, and TOC page-number entries – evaluate to a placeholder 0, because this edition does not include the page-layout/rendering engine.
  • Register IFieldUpdatingCallback before running Range.UpdateFields() over a large or unfamiliar document if you need to log or audit exactly which fields changed.
  • Set FieldOptions.UserPromptRespondent (or supply DefaultResponse values on the individual prompt-driven field classes) before updating a document in an unattended pipeline, so ASK/FILLIN fields do not stall waiting for interactive input.

Common Issues

IssueCauseFix
Field result is out of date after editing the documentAspose.Words FOSS does not auto-update fields on load or saveCall Range.UpdateFields() or Field.Update() explicitly
PAGE, NUMPAGES, or TOC page numbers show 0Page layout/rendering is not part of this editionExpected behavior – use the commercial Aspose.Words for .NET if you need computed page numbers
DATABASE field produces no rowsNo IFieldDatabaseProvider is assigned to FieldOptions.FieldDatabaseProviderImplement IFieldDatabaseProvider and assign it before calling Range.UpdateFields()
Batch field update appears to hangA prompt-driven field (ASK, FILLIN) has no IFieldUserPromptRespondent assignedAssign FieldOptions.UserPromptRespondent, or set DefaultResponse on the field instance

FAQ

Does Aspose.Words FOSS evaluate every Word field type?

The Field object model represents every FieldType value and updates most of them, but fields whose result depends on page layout – such as PAGE and NUMPAGES – evaluate to a placeholder 0 because this edition does not include the layout/rendering engine.

How do I re-evaluate fields after editing a document programmatically?

Call Range.UpdateFields() on the range that covers the edited content, or Document.Range.UpdateFields() to update every field in the document.

Can I convert a field to plain, static text?

Yes – Field.Unlink() replaces the field with its last-calculated result as ordinary text, removing the underlying field code.

How do I remove a field completely, including its result?

Call Field.Remove(). It deletes the FieldStart, Separator, and FieldEnd nodes together with the field’s code and result content.

How do I supply custom data to the DATABASE field?

Implement IFieldDatabaseProvider and assign it to Document.FieldOptions.FieldDatabaseProvider. Your GetQueryResult() implementation returns a FieldDatabaseDataTable built from FieldDatabaseDataRow instances.


API Reference Summary

Class / InterfaceDescription
FieldBase class for a Word field; GetFieldCode(), Update(), Unlink(), Remove()
FieldCollectionThe fields in a range, via Range.Fields; Count, Remove(), Clear()
FieldTypeEnum identifying which Word field a Field instance represents
FieldOptionsDocument-wide field update configuration, via Document.FieldOptions
IFieldUpdatingCallbackFieldUpdating / FieldUpdated hooks around each field update
IFieldUpdatingProgressCallback / FieldUpdatingProgressArgsProgress reporting across a bulk field update
IFieldResultFormatterCustom formatting of a field’s calculated result
IFieldDatabaseProvider / FieldDatabaseDataTable / FieldDatabaseDataRowExternal data source for the DATABASE field
IComparisonExpressionEvaluator / ComparisonExpression / ComparisonEvaluationResultCustom evaluation of comparison-style field expressions
IFieldUserPromptRespondentSupplies responses for prompt-driven fields in unattended updates
IFieldUpdateCultureProvider / FieldUpdateCultureSourceCulture selection during field updates
UserInformationAuthor/user identity (Name, Initials, Address) read by identity fields