TX Text Control .NET for Windows Forms

Form Fields and Conditional Instructions

Topic

Booking requests, applications and questionnaires are documents in which users fill in only some places: a text box, a check box, a drop-down list or a date. With form fields, a Windows Forms application designs such forms in a TextControl, protects everything else, reads what users enter and checks the entries with conditional instructions, rules that validate, enable or fill fields depending on other fields.

The examples extend the application of Create Your First Windows Forms Application, and Form1.cs needs using TXTextControl;. Form fields were introduced in version 28.0 and are part of the Enterprise edition; see Editions and Feature Availability. Create a PDF Form is a short tutorial that turns form fields into a fillable PDF.

Form Field Types

A form field is a field that users fill out. All form fields derive from FormField, which is a TextField, and all of them are in the collection TextControl.FormFields:

Form fieldClassWhat the user does
Text form fieldTextFormFieldTypes text
Check boxCheckFormFieldChecks or unchecks it
Drop-down listSelectionFormField with Editable set to falseChooses one of the items
Combo boxSelectionFormField with Editable set to trueChooses an item or types a value
Date form fieldDateFormFieldPicks a date in a date picker or types it

Design a Form With the Ribbon

The Form Fields tab of the ribbon, RibbonFormFieldsTab, inserts all five types from the Insert Form Fields button. Its other groups edit, delete and navigate form fields, set up form validation and show the properties of the selected field, such as its name and the items of a drop-down list:

The Form Fields tab of TX Text Control Words with a booking request form: a date field, two text fields and an open drop-down list, and the drop-down list properties in the ribbon.

To add the tab to your form, click the smart tag of the ribbon in the designer and click Add a RibbonFormFieldsTab, as in Create Your First Windows Forms Application. In code, FormField.FormFieldDialog opens the built-in dialog box of a form field.

Insert Form Fields in Code

The following handler writes a small booking form: a label, then a form field, for each of the four types:

private void insertFormButton_Click(object sender, EventArgs e)
{
    textControl1.Selection.Text = "Arrival: ";
    AddFormField(new DateFormField(0) { Name = "Arrival" });

    textControl1.Selection.Text = "\nNumber of nights: ";
    AddFormField(new TextFormField(1000) { Name = "Nights" });   // width in twips while empty

    textControl1.Selection.Text = "\nAccommodation: ";
    AddFormField(new SelectionFormField(new string[] { "Single room", "Double room", "Suite" }, -1)
    {
        Name = "Accommodation",
        Editable = false   // false: drop-down list, true: combo box
    });

    textControl1.Selection.Text = "\nBreakfast: ";
    AddFormField(new CheckFormField(false) { Name = "Breakfast" });
}

// Insert a form field and move the input position behind it
private void AddFormField(FormField formField)
{
    textControl1.FormFields.Add(formField);
    textControl1.InputPosition = new InputPosition(
        formField.Start + formField.Length - 1,
        TextFieldPosition.OutsideTextField);
}

The code works as follows:

Each type has its own settings: SelectionFormField.Items for the list, CheckFormField.Checked with the characters for both states, and DateFormField.Date with a DateFormat, which uses the format of the text's culture when it is empty. FormField.Enabled set to false keeps users from filling in a single field of a protected form.

Let Users Fill Out the Form

A form is ready for users when everything except the form fields is protected. Users of TX Text Control Words do this on the Permissions tab: they select Fill in Form Fields and Read Only and click Enforce Protection, optionally with a password.

The Permissions tab with Fill in Form Fields, Read Only and Enforce Protection selected, and the Enforce Protection dialog box asking for an optional password.

In code, it takes three settings:

private void protectFormButton_Click(object sender, EventArgs e)
{
    // Users can fill in the form fields and change nothing else
    textControl1.DocumentPermissions.AllowEditingFormFields = true;
    textControl1.DocumentPermissions.ReadOnly = true;
    textControl1.EditMode = EditMode.ReadAndSelect;
}

Document Protection and Editable Regions explains document permissions, passwords and editable regions.

Read the Values

The values are in the form fields: the Text of text, selection and date fields, Checked of check boxes and Date of date fields:

private void readValuesButton_Click(object sender, EventArgs e)
{
    StringBuilder values = new StringBuilder();

    foreach (FormField formField in textControl1.FormFields)
    {
        string value = formField switch
        {
            CheckFormField checkField => checkField.Checked ? "yes" : "no",
            DateFormField dateField => dateField.Date?.ToShortDateString() ?? "",
            _ => formField.Text
        };

        values.AppendLine(formField.Name + ": " + value);
    }

    MessageBox.Show(values.ToString());
}

StringBuilder needs using System.Text;. To react to each entry, handle one event per type. Each handler receives the field that has changed:

EventOccurs whenEvent arguments
FormFieldTextChangedThe text of a text form field has been changed and the field is leftTextFormFieldEventArgs
FormFieldCheckChangedA check box has been checked or uncheckedCheckFormFieldEventArgs
FormFieldSelectionChangedAn item has been selected, or a new text typed and the field leftSelectionFormFieldEventArgs
FormFieldDateChangedA date has been picked, or a valid date typed and the field leftDateFormFieldEventArgs
public Form1()
{
    InitializeComponent();
    textControl1.FormFieldCheckChanged += textControl1_FormFieldCheckChanged;
}

private void textControl1_FormFieldCheckChanged(object sender, CheckFormFieldEventArgs e)
{
    Text = e.CheckFormField.Name + ": " + e.CheckFormField.Checked;
}

The events report changes made by the user. They aren't raised when your code changes a value through a property such as CheckFormField.Checked, SelectionFormField.SelectedIndex or DateFormField.Date.

Validate Entries With Conditional Instructions

A conditional instruction consists of conditions on the values of form fields and instructions that are carried out when the conditions are fulfilled. An instruction can enable or disable a form field, mark its value as valid or invalid, set a value, or replace the items of a drop-down list. For example: "If the number of nights is less than 2 or greater than 14, mark it as invalid." The rules are stored in the document and run while the form is filled out, so the form checks itself without code in your application.

Users work with conditional instructions in the Form Validation group of the Form Fields tab: Enable Form Validation turns validation on, Manage Conditional Instructions shows the Conditional Instructions sidebar with the rules of the document, and Highlight Invalid Values marks the values that a rule has found invalid. In your form, connect the sidebar with the ConditionalInstructionsSidebar property of the tab; Sidebar and Panels describes sidebars.

TX Text Control Words with the Form Fields tab, the booking request form and the Conditional Instructions sidebar showing the conditions and actions of Validate Arrival.

Conditional Instructions explains how to turn on validation, create rules in the dialog box and in C#, combine conditions, use else, initial and change instructions and check invalid values, and builds the complete rules of a booking form.

The TX Text Control Words sample Conditional Instructions, installed in %USERPROFILE%\Documents\TX Text Control 34.0.NET for Windows Forms\CSharp\TX Words\Conditional Instructions, loads a booking form with conditional instructions and previews it as a protected form. The blog article Building a Credit Card Payment Form with Conditional Instructions builds a complete form with rules.

Preview the Form

While you design a form, you want to try out its rules without losing the unprotected template. The TX Text Control Words sample Conditional Instructions does this with a Preview button: it saves the document and its permissions, protects the document as a form and, when the preview ends, loads the saved document again. The following handler is a toggle button of the same kind; it needs IsFormFieldValidationEnabled to be true, because otherwise the rules don't run:

private byte[] formTemplate;
private bool savedAllowEditingFormFields;
private bool savedReadOnly;

private void previewButton_Click(object sender, EventArgs e)
{
    if (formTemplate == null)
    {
        // Keep the template and its permissions
        textControl1.Save(out formTemplate, BinaryStreamType.InternalUnicodeFormat);
        savedAllowEditingFormFields = textControl1.DocumentPermissions.AllowEditingFormFields;
        savedReadOnly = textControl1.DocumentPermissions.ReadOnly;

        // Protect the document as a form: the initial instructions run
        textControl1.DocumentPermissions.AllowEditingFormFields = true;
        textControl1.DocumentPermissions.ReadOnly = true;
        textControl1.EditMode = EditMode.ReadAndSelect;
    }
    else
    {
        // Loading the template also resets the edit mode
        textControl1.Load(formTemplate, BinaryStreamType.InternalUnicodeFormat);
        formTemplate = null;

        textControl1.DocumentPermissions.AllowEditingFormFields = savedAllowEditingFormFields;
        textControl1.DocumentPermissions.ReadOnly = savedReadOnly;
    }
}

The code works as follows:

  • Save with BinaryStreamType InternalUnicodeFormat writes the whole document to a byte array in the TX Text Control format.
  • The three settings of Let Users Fill Out the Form turn the document into a form. Everything the user enters during the preview changes only this copy.
  • Load with the same byte array brings back the template as it was before the preview. The edit mode doesn't have to be reset, because loading the saved content already does that; the two document permissions are restored by hand.

The sample also hides the ribbon groups to the right of Form Validation and disables Enable Form Validation while the preview is on. Turn on Highlight Invalid Values to see which values the rules mark as invalid. The Preview button is at the right of the Form Validation group, as the picture in Validate Entries With Conditional Instructions shows.

Save and Export Forms

Form fields are saved and loaded with the TX Text Control format and with DOC, DOCX and RTF. When a Word document is loaded, its form fields become TX Text Control form fields, unless LoadSettings.ApplicationFieldFormat loads them as MS Word fields. Saved as PDF, form fields become fillable PDF form fields with their names and values; PDF Forms shows how to create, read and flatten PDF forms, and Forms and Conditional Instructions in Document Processing works with form fields without a user interface.

Next Steps