Using Text Fields and Hypertext Links

TX Text Control offers a set of classes to define text positions or pieces of text in the document with a special meaning. These pieces of text are called marked text fields. They can be used to create hypertext features, to realize database embedding while text of different datasets can be included into the text or to combine several fields with formulas as in spreadsheet applications. Code examples can be found in the User's Guide chapters Using Marked Text Fields, Using Hypertext Links, Mail Merge and Connecting to Databases.

Overview of the TextField and Hypertext Link Classes

The base class for all types of text fields is the TextField class. It implements the base functionality of marked text fields like text and position, editing features, and data and event handling. These base features are explained later in this article. Additional classes, all of which are derived from the TextField class, are available for special types of marked text fields. These are listed in the following table:

Class Description
TextField Class Implements a general text field. It can be used to handle database fields, spreadsheet features or bookmarks.
HypertextLink Class Derived class that implements a hypertext link. It can be used for links that point to targets outside of the current document.
DocumentLink Class Derived class that can be used for links that point to targets inside of the current document.
DocumentTarget Class Derived class that implements a target in a document.
PageNumberField Class Derived class that implements a field that automatically shows the current page number. This field can only be used in a header or a footer.
ApplicationField Class Derived class that implements a field providing an interface to retrieve and change the data and parameters of Microsoft Word fields and Heiler HighEdit fields.

For each type of text field, a Text Control manages a collection containing all fields of the same type. The collections can be used to add or remove fields, to get a individual item or to enumerate all fields of a certain type. Each collection is available through a readonly property of the TextControl, WPF.TextControl and ServerTextControl classes. The collection of page number fields can only be obtained through a property of the HeaderFooter class. The following table lists all available collections and their corresponding properties:

Collection Class Obtaining Property
TextFieldCollection TextControl.TextFields, WPF.TextControl.TextFields, ServerTextControl.TextFields, HeaderFooter.TextFields
HypertextLinkCollection TextControl.HypertextLinks, WPF.TextControl.HypertextLinks, ServerTextControl.HypertextLinks
DocumentLinkCollection TextControl.DocumentLinks, WPF.TextControl.DocumentLinks, ServerTextControl.DocumentLinks
DocumentTargetCollection TextControl.DocumentTargets, WPF.TextControl.DocumentTargets, ServerTextControl.DocumentTargets
PageNumberFieldCollection HeaderFooter.PageNumberFields
ApplicationFieldCollection TextControl.ApplicationFields, WPF.TextControl.ApplicationFields, ServerTextControl.ApplicationFields

Editing Text Fields

Text fields can be edited by the end-user like any other text in the document. To prevent changing the text of a text field, the TextField.Editable property can be used. If the text of a text field may be changed by the end-user but the text field itself must not be deleted, the TextField.Deleteable property can be set to false. In this case, the text of the field can be altered but a selection containing the field in the middle, cannot be deleted or replaced.

If a marked text field is fully editable, the two text input positions at the beginning and the end of a marked text field have a special meaning. If an end-user inserts text at one of these positions, it is not unique whether or not the newly inserted text belongs to the field. To solve this problem, the TextField class offers the DoubledInputPosition property. This implements a second input position, which the end-user can reach with the Left Arrow and Right Arrow keyboard keys.

Additionally, a visual feedback for the end-user can be set with the TextField.ShowActivated property. If this property is set to true, an actived text field is displayed with a gray background. A text field is defined as activated, if the current text input position is inside the field so that the next inserted character is added to the text of the field. If the mouse cursor is moved over a text field, it is changed to a hand cursor to indicate that there is a field. The hand cursor can be changed to another shape using the TextControl.FieldCursor property.

During editing, the application is informed through the following events of the TextControl class:

Event Description
TextControl.TextFieldChanged Event Occurs when the text of a text field has been changed. It does not occur, if formatting attributes of the field's text have been altered or if the text of the field has been changed from program code with the TextField.Text property.
TextControl.TextFieldClicked Event Occurs when a text field has been clicked with the mouse.
TextControl.TextFieldDoubleClicked Event Occurs when a text field has been double-clicked with the mouse. It does not occur, if the TextField.DoubleClickEvent property has been set to false.
TextControl.TextFieldEntered Event Occurs when the current input position has been moved from a position outside of a field to a position that belongs to a field. This only occurs, if an end-user has entered a field using the keyboard or a mouse-click. It does not occur, if the field has been entered through program code.
TextControl.TextFieldLeft Event Occurs when the current input position has left a text field. It occurs only, if a field has been left trough an end-user with the keyboard or a mouse-click. It does not occur if the field has been left through program code.

All event handlers for these events receive an argument of the type TextFieldEventArgs . This class has a TextField property through which the field that has caused the event can be obtained.

All derived classes of the TextField class mentioned above inherit the editing features so that these are also available for hypertext links and page number fields. Each of the described attributes can be defined for a single field in any combination, which means that different kinds of marked text fields can be implemented in a single Text Control.

Inserting and Deleting Text Fields

Text fields can be inserted into a Text Control either by adding them to one of the field collections or with the TextControl.Load method as a part of a document. The following programming code creates a new text field, obtains the TextFieldCollection object and adds the field using the TextFieldCollection.Add method:

TextField newField = new TextField("new field");
newField.ShowActivated = true;
newField.DoubledInputPosition = true;
Dim NewField As New TextField("new field")
NewField.ShowActivated = True
NewField.DoubledInputPosition = True

This code inserts a text field that is shown with a gray background and with a doubled input position at the beginning and the end, as explained in the chapter Editing Marked Text Fields.

A new field is always inserted at the current input position. If there is already a field an error occurs. To get the information whether a text field can be inserted at the current input position the CanAdd property can be used. To insert a field at a position other than the current one, first move the input position using the following code:

TextField newField = new TextField("new field");
textControl1.InputPosition = new InputPosition(1, 3, 0);
Dim NewField As New TextField("new field")
TextControl1.InputPosition = New InputPosition(1, 3, 0)

This code inserts the field on the first page, in the third line, at position zero. position zero is the position in front of the first character.

To remove a marked text field from the document use the collection's Remove method as shown with the following code:

TextFieldCollection tfc = textControl1.TextFields;
TextField textField = tfc.GetItem(200);
if (textField != null) {
Dim tfc As TextFieldCollection = TextControl1.TextFields
Dim Field As TextField = tfc.GetItem(200)
If Not Field Is Nothing Then
End If

This code removes the text field with the identifier 200. How to relate and use identifiers for text fields is described in the chapter Identifiers and Names.

If a text field is added during editing, a TextControl.TextFieldCreated event occurs. This can happen, if a piece of text containing a field is inserted from the clipboard, or if a field is restored through an undo/redo operation. This event does not occur, if a document containing fields is loaded, or if a field is added from programming code.

If a text field is deleted during editing, a TextControl.TextFieldDeleted event occurs. This can happen, if a selection of text containing a field is deleted, or if a field is deleted through an undo/redo operation. The event does not occur, if a field is deleted from program code.

The event handlers for these events also receive an argument of type TextFieldEventArgs. The TextField object that can be obtained through the TextField property identifies the field that has caused the event. If a field has been deleted, only the TextField.ID and the Textfield.Name properties provide valid values.

Identifiers and Names for Text Fields and Hypertext Links

A Text Control can manage an identfier and/or a name for each text field. These data can be specified with the TextField.ID and TextField.Name properties. For example, when a Text Control is used to show the contents of a database, a marked text field can be created for each database field. The database's field names can then be related to the text fields using the TextField.Name property. If something then happens with the field and an event occurs, the TextField.Name property informs, which field has caused the event. The following code inserts a field presenting a price:

TextField newField = new TextField("$ 22.45");
newField.Name = "Price";
Dim NewField As New TextField("$ 22.45")
NewField.Name = "Price"

When a marked text field is copied via the clipboard or saved to a file, the id and/or name belonging to the field are also copied or saved. If a field is copied via the clipboard, a TextControl.TextFieldCreated event occurs so that the programmer has the opportunity to change the id and/or name to avoid multiple occurrences. The following code shows an installed event handler for the TextFieldCreated event. This event occurs after the end-user has copied via the clipboard the field created above. The Name property of the created field is changed so that other code can distinguish between the two fields:

        += new TextFieldEventHandler(textControl1_TextFieldCreated);
private void textControl1_TextFieldCreated(object sender, TextFieldEventArgs e) {
    if (e.TextField.Name == "Price") {
        e.TextField.Name = "Copy of Price";
Private Sub TextControl1_TextFieldCreated(ByVal sender As Object, _
        ByVal e As TextFieldEventArgs) Handles TextControl1.TextFieldCreated
    If e.TextField.Name = "Price" Then
        e.TextField.Name = "Copy of Price"
    End If
End Sub

Any string data can be assigned to the Name property. The number of characters is not limited so that even a large text can be related to a field.

Inserting Page Numbers

In a header or footer, accessible through the HeaderFooter class, special placeholders for page numbers can be inserted. Such a placeholder is defined through the PageNumberField class, also derived from the TextField class. Using such a field, a header or footer automatically shows the current page number or the total number of pages on every page.

Page number fields inherit the editing features of the TextField class and have additionally a NumberFormat, a StartNumber and a ShowNumberOfPages property. The NumberFormat property specifies the kind of numbers used to display the page numbers. Possible values are Arabic numbers, small and large Roman numbers, letters and capital letters. The StartNumber property defines the starting page number for the first page of the section. The ShowNumberOfPages property specifies whether the field shows the page number or the total number of pages.

For each section in the document, page numbers can either be continued from the previous section or can be restarted with a certain start number. The SectionFormat class provides the SectionFormat.RestartPageNumbering property to adjust this setting.

The following code adds a header to the current section. After insertion, the header receives a text, the current page number and total number of pages fields:

HeaderFooterCollection hfc = textControl1.Sections.GetItem().HeadersAndFooters;


HeaderFooter h = hfc.GetItem(HeaderFooterType.Header);
if (h != null)
    h.Selection.Text = "Page  of ";
    h.Selection.Start = 5;
    h.Selection.Length = 0;

    PageNumberField page = new PageNumberField(1, NumberFormat.ArabicNumbers);
    page.Editable = false;
    page.DoubledInputPosition = true;

    h.Selection.Start = 9;
    h.Selection.Length = 0;

    PageNumberField totalPages = new PageNumberField();
    totalPages.Editable = false;
    totalPages.DoubledInputPosition = true;
    totalPages.ShowNumberOfPages = true;
Dim hfc As HeaderFooterCollection = textControl1.Sections.GetItem().HeadersAndFooters


Dim h As HeaderFooter = hfc.GetItem(HeaderFooterType.Header)
If h IsNot Nothing Then
    h.Selection.Text = "Page  of "
    h.Selection.Start = 5
    h.Selection.Length = 0

    Dim page As New PageNumberField(1, NumberFormat.ArabicNumbers)
    page.Editable = False
    page.DoubledInputPosition = True

    h.Selection.Start = 9
    h.Selection.Length = 0

    Dim totalPages As New PageNumberField()
    totalPages.Editable = False
    totalPages.DoubledInputPosition = True
    totalPages.ShowNumberOfPages = True
End If

After the header has been inserted in the document, it receives the text Page of with a space after Page and at the end. Because a header has no Text property, this is done by replacing the text of the current text selection using the Selection class. Initially, a newly inserted header has no text, therefore the initial text selection has a length of zero so that the new text is inserted.

Afterwards, the current text input position is set between Page and of where the page number field is inserted. This field is set to not editable, so that an end-user cannot change its current text. To enable text insertion right of the page number, a second input position is needed. This can be reached by pressing the Right Arrow key at the text end.

After that, the input position is set to the end to insert the total number of pages field.

Importing Fields from Microsoft Word

TX Text Control supports field formats of other applications such as Microsoft Word. The ApplicationField class provides an interface to retrieve and change the data and parameters of such fields. Currently supported formats are the Microsoft Word Field Format, the format of Microsoft Word Form Fields and the field format of the Heiler HighEdit component. Because these formats are not compatible, the user must specify the format when a document is loaded. The following code imports all MergeField and PrintDate fields contained in an RTF document that has been created with Microsoft Word:

LoadSettings ls = new LoadSettings();
ls.ApplicationFieldFormat = ApplicationFieldFormat.MSWord;
ls.ApplicationFieldTypeNames = new string[] { "MERGEFIELD", "PRINTDATE" };
textControl1.Load("c:\test.rtf", TXTextControl.StreamType.RichTextFormat, ls);
Dim ls As New LoadSettings
ls.ApplicationFieldFormat = ApplicationFieldFormat.MSWord
ls.ApplicationFieldTypeNames = New String() {"MERGEFIELD", "PRINTDATE"}
TextControl1.Load("c:      est.rtf", TXTextControl.StreamType.RichTextFormat, ls)

After the document has been loaded all MergeField and PrintDate fields are available through the TextControl.ApplicationFields collection. The collection contains objects of the type ApplicationField. The ApplicationField class has a TypeName property specifying the field's type and a Parameters property specifying the field's parameters as an array of strings. The following is the format of a MergeField defined through Microsoft Word:

MERGEFIELD FieldName [Switches]

For example: MERGEFIELD Address \* Upper \v

For further information about the switches and it's meaning, please refer to Microsoft's Field Reference.

In this example the FieldName is Address and there are two switches specifying some formatting options. The ApplicationField.Parameters array then contains three elements, the first of which is the FieldName and the others are the switches.

The following code iterates through all fields imported with the example above and sets the visible text of the address field:

foreach (ApplicationField appField in textControl1.ApplicationFields) {
    if (appField.TypeName == "MERGEFIELD" && appField.Parameters[0] == "Address") {
        appField.Text = "Bakerstreet, London";
For Each appField As ApplicationField In TextControl1.ApplicationFields
    If appField.TypeName = "MERGEFIELD" And appField.Parameters(0) = "Address" Then
        appField.Text = "Bakerstreet, London"
    End If

To add to or remove elements from the Parameters string array a new array must be constructed because .NET arrays have a fixed size. The following code looks for a \v switch and removes it from the parameters array. First a new array is created and the remaining strings that can be in front or behind the searched string are copied:

foreach (ApplicationField appField in textControl1.ApplicationFields) {
    string[] params = appField.Parameters;
    int index = Array.IndexOf(params, "\v");
    if (index >= 0) {
        string[] newParams = new string[params.Length-1];
        if (index > 0) {
            Array.Copy(params, newParams, index);
        if (params.Length-index-1 > 0) {
            Array.Copy(params, index+1, newParams, index, params.Length-index-1);
        appField.Parameters = newParams;
For Each appField As TXTextControl.ApplicationField In TextControl1.ApplicationFields
    Dim params() As String = appField.Parameters
    Dim index As Integer = Array.IndexOf(params, "")

    If index >= 0 Then
        Dim newParams(params.Length - 2) As String
        If index > 0 Then
            Array.Copy(params, newParams, index)
        End If
        If params.Length - index - 1 > 0 Then
            Array.Copy(params, index + 1, newParams, index, params.Length - index - 1)
        End If

        appField.Parameters = newParams
    End If

TX Text Control also supports importing and exporting of Microsoft Word form fields. These fields can be imported specifying FORMCHECKBOX, FORMDROPDOWN or FORMTEXTBOX with the LoadSettings.ApplicationFieldTypeNames property. Microsoft Word form fields also have parameters, that can be edited in Microsoft Word with the Form Field Options dialog box. TX Text Control provides these parameters through the ApplicationField.Parameters property using the XML syntax of the Office Open XML Format.

To learn more about the Office Open XML Format, please refer to the official ECMA standard.

MS Word implements another feature to support individual controls like form elements in templates or forms: Content Controls. The following controls are available since MS Word 2007: Rich Text, Text, Picture, Combo Box, Drop-Down List and Check Box.

Just like for the merge and form fields, TX Text Control imports these fields as ApplicationFields available in the ApplicationField collection. TX Text Control provides parameters through the ApplicationField.Parameters property using the XML syntax of the Office Open XML Format. The content controls have the ApplicationField.TypeName SDTBLOCK. The type of the control is defined in the XML of the ApplicationField.Parameters property. The w:val parameter of the w:tag defines the type. The following types are available:

Content Control Description
Rich Text Control Text content that contains formatting.
Plain Text Control Limited to content that cannot contain any formatting, only plain text.
picture Fills the content control with a single picture.
Combo Box Contains a list that can be edited directly.
Check Box Provides a check box users can check and uncheck. The checked value is stored in the XML data.
dropDownList Contains a list of restricted choices defined by the template author when the user activates the drop-down box.

Please refer to the official Microsoft Office documentation to learn more about the various content controls.