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.
The base class for almost all types of text fields is the TextField class. It implementsthe base functionality of text fields like text and position, editing features, and data and event handling. These base features are explained later in this article. Additional classes, the most of which arederived from the TextField class, are available for special tasks. These are listed in the following table:
Class | Description |
---|---|
Text |
Implements a general text field. It can be used to handle database fields or spreadsheet features. |
Hypertext |
Derived class that implements a hypertext link. It can be used for links that point to targets outside of the current document. |
Document |
Derived class that can be used for links that point to targets inside of the current document. |
Page |
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. |
Application |
Derived class that implements a field providing an interface to retrieve and change the data and parameters of Microsoft Word fields and Heiler High |
Form |
Derived class that implements the base class for all formfields. |
Check |
Derived class representing a checkbox that can be checked or unchecked through the end-user. |
Selection |
Derived class that offers the end-user a combobox or a drop-down list. |
Text |
Derived class that represents a text input field on a form. When it is empty it can be set to a specified width. |
Date |
Derived class that can be used to manage and format a date. |
Document |
Implements a target or a bookmark in a document. |
For each of these classes, a Text Control manages a collection containing all instances of the same type. The collections can be used to add or remove fields, to get an individual item or to enumerate all fields of a certain type. Each collection is available through a readonly property of the TextControl, WPF.TextControl, ServerTextControl, TextFrame and HeaderFooter 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 |
---|---|
Text |
Text |
Hypertext |
Text |
Document |
Text |
Document |
Text |
Page |
Header |
Application |
Text |
Form |
Text |
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 |
---|---|
Text |
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. |
Text |
Occurs when a text field has been clicked with the mouse. |
Text |
Occurs when a text field has been double-clicked with the mouse. It does not occur, if the Text |
Text |
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. |
Text |
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.
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.
A Text Control can manage an identfier and/or a name for each text field. These data can be specifiedwith the TextField.ID and TextField.Name properties. For example, when a Text Control is used to show the contents of a database, a 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.Nameproperty 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";
txTextControl1.TextFields.Add(newField);
Dim NewField As New TextField("$ 22.45")
NewField.Name = "Price"
TextControl1.TextFields.Add(NewField)
When a 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, aTextControl.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 eventhandler for the TextFieldCreated event. This event occursafter 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:
textControl1.TextFieldCreated
+= 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.
Hypertext links are connection points with other text positions in the same or another document.TX Text Control distinguishes between links that point to text positions in the same document and links that point to other documents. Links that point to another document are called hypertext links and are encapsulated through the HypertextLink class.
A link to another position in the same document is called a document link, encapsulated through the DocumentLink class. The position to which the link points can also be defined through the programmer. It is called a document target and can be specified with the DocumentTarget class.
For each type of these objects, a Text Control maintains a collection to enable the programmer to add,remove or manipulate an item. An appropriate property of the TextControl class as described in the chapter TextField Classes enables access to the collection.
The following code defines a link and a target inside a TextControl document. It first defines a targetat the top of the document's second page and then creates a hypertext link that points to this target:
int curPosition = textControl1.InputPosition.TextPosition;
DocumentTarget target = new DocumentTarget("Second Page");
textControl1.InputPosition = new InputPosition(2, 1, 0);
textControl1.DocumentTargets.Add(target);
textControl1.InputPosition = new InputPosition(curPosition);
DocumentLink link = new DocumentLink("Goto second page", target);
textControl1.DocumentLinks.Add(link);
Dim curPosition As Integer = TextControl1.InputPosition.TextPosition
Dim Target As New DocumentTarget("Second Page")
TextControl1.InputPosition = New InputPosition(2, 1, 0)
TextControl1.DocumentTargets.Add(Target)
TextControl1.InputPosition = New InputPosition(curPosition)
Dim Link As New DocumentLink("Goto second page", Target)
TextControl1.DocumentLinks.Add(Link)
Before setting the input position to the second page, the old position is saved. The old position is restoredbefore inserting the link. The target's constructor receives a name for the target.In addition to the target name, other string data can still be stored, using the document target'sName property.
There is no automatic linking implemented for a link-target pair in a Text Controldocument, because applications handle clicks differently depending on whether additional keyboard keys arepressed. To implement linking use the target's ScrollTo method when a user has clicked ontoa link as shown with the following code example:
textControl1.DocumentLinkClicked
+= new DocumentLinkEventHandler(textControl1_DocumentLinkClicked);
private void textControl1_DocumentLinkClicked(object sender, DocumentLinkEventArgs e) {
if (Control.ModifierKeys == Keys.Control) {
e.DocumentLink.DocumentTarget.ScrollTo();
}
}
Private Sub TextControl1_DocumentLinkClicked(ByVal sender As Object, _
ByVal e As DocumentLinkEventArgs) Handles TextControl1.DocumentLinkClicked
If Control.ModifierKeys = Keys.Control Then
e.DocumentLink.DocumentTarget.ScrollTo()
End If
End Sub
This code implements an event handler for the TextControl.DocumentLinkClicked event. The handler's code scrolls to the target that is connected with the link that has caused the event. This occursonly, if the CTRL keyboard key is pressed.
Hypertext links to other documents are treated similarly. They are inserted or deleted with theHypertextLinkCollection class. A click on such a link results in a TextControl.HypertextLinkClicked event. The application has to provide the code for thelinking action.
All editing features, as described in the chapter Editing Text Fields, can also be used for hypertextlinks. Relating string data and identifiers as described in the chapter Names and Identifiers is also possible for links.Further code examples can be found in the User's Guide chapter Using Hypertext Links.
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.
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. |
drop |
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: