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 text fields. They can be used to create hypertext features or to realize database embedding while text of different datasets can be included into the text.

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 thiscase, the text of the field can be altered but a selection containing the field in the middle, cannot be deleted orreplaced.

If a text field is fully editable, the two text input positions at the beginning and the endhave 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 Arrowand Right Arrow keyboard keys or through a mouse-click left or right of these input positions.

Additionally, a visual feedback for the end-user can be set with the TextField.HighlightMode property. If this property is set to HighlightMode.Activated, an activated text field is highlighted with a colored 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 field's text. If the mouse cursor is movedover 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 TextControlclass:

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'stext have been altered.
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 text input position has been moved from a position outside of a field to a position that belongs to a field.
TextControl.TextFieldLeft Event Occurs when the current text input position has left a text field.

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 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 fieldcollections or with the TextControl.Load method as a part of a document. The followingprogramming code creates a new text field, obtains the TextFieldCollection object and adds thefield using the TextFieldCollection.Add method:

TextField newField = new TextField("new field");
newField.HighlightMode = HighlightMode.Activated;
newField.DoubledInputPosition = true;
textControl1.TextFields.Add(newField);
Dim NewField As New TextField("new field")
NewField.HighlightMode = HighlightMode.Activated
NewField.DoubledInputPosition = True
TextControl1.TextFields.Add(NewField)

This code inserts a text field that is shown with a gray background and with a doubled inputposition at the beginning and the end as explained in the chapter Editing 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 fieldcan be inserted at the current text input position the CanAdd property canbe used. To insert a field at a position other than the current one, first move the input positionusing the following code:

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

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 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) {
    tfc.Remove(textField);
}
Dim tfc As TextFieldCollection = TextControl1.TextFields
Dim Field As TextField = tfc.GetItem(200)
If Not Field Is Nothing Then
    tfc.Remove(Field)
End If

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

If a text field is added, 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.

If a text field is deleted, a TextControl.TextFieldDeleted event occurs. This can happen, if a selection of text containing a field is deleted, or if a field is deletedthrough an undo/redo operation.

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 theevent. If a field has been deleted, only the TextField.ID and the Textfield.Nameproperties provide valid values.

Inserting Page Numbers

In a header or footer, accessible through the HeaderFooter class, specialplaceholders 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 additionallya NumberFormat, a StartNumber and a ShowNumberOfPages property. TheNumberFormat property specifies the kind of numbers usedto display the page numbers. Possible values are Arabic numbers, small and large Roman numbers,letters and capital letters. The StartNumber propertydefines 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;

hfc.Add(HeaderFooterType.Header);

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.PageNumberFields.Add(page);

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

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

hfc.Add(HeaderFooterType.Header)

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.PageNumberFields.Add(page)

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

    Dim totalPages As New PageNumberField()
    totalPages.Editable = False
    totalPages.DoubledInputPosition = True
    totalPages.ShowNumberOfPages = True
    h.PageNumberFields.Add(totalPages)
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 byreplacing 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, sothat an end-user cannot change its current text. To enable text insertion right of the page number, a secondinput position is needed. This can be reached by pressing the Right Arrow key at thetext 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:

http://www.textcontrol.com/in/msofficefieldreference.htm

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
Next

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
Next

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:

http://www.textcontrol.com/in/ecmaofficeopenxmlfileformats.htm

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:

http://www.textcontrol.com/in/msofficecontentcontrols.htm