TX Text Control .NET for Windows Forms

Search and Replace

Topic

Finding a word, a customer name or a placeholder in a long document, and replacing it, is a standard task of a word processor. TextControl brings built-in Find and Replace dialog boxes and sidebars for users, and a Find method with which your code locates text and replaces it without any user interface.

The examples extend the form of Create Your First Windows Forms Application, whose editor is named textControl1. Selecting found text relies on the text positions explained on Selections and Caret Position.

Find and Replace for Users

The Home tab of the ribbon has an Editing group with Find..., Replace... and Go to.... The buttons open dialog boxes, or sidebars if your form connects them.

Find without parameters opens the built-in Find dialog box, and Replace opens the Replace dialog box. Call them from any button or menu item of your form:

private void FindButton_Click(object sender, EventArgs e)
{
    textControl1.Find();
}

private void ReplaceButton_Click(object sender, EventArgs e)
{
    textControl1.Replace();
}

The Replace dialog box offers options to match case, to match whole words only and to search upward. Besides the main text, it can search text frames and headers and footers.

The Replace dialog box of TX Text Control in front of an invoice, with the Find what and Replace with boxes, the find options and the Find Next, Replace, Replace All and Cancel buttons.

The built-in keyboard assignment of the editor doesn't include Ctrl+F or Ctrl+H. Keyboard Shortcuts shows how to add them.

Find and Replace in a Sidebar

A Sidebar shows the same functions as a panel beside the document when its ContentLayout is Find or Replace. Connected to the FindSidebar and ReplaceSidebar properties of the RibbonFormattingTab, it opens when the user clicks Find or Replace; Sidebar and Panels describes the setup.

Find Text in Code

Find has two overloads that search without a dialog box and return a zero-based text position:

OverloadSearches
Find(string text)From the beginning of the text
Find(string text, int start, FindOptions options)From start, or from the input position if start is -1, with the given options

Both return the position of the first character of the match, or -1 if the text doesn't occur. They search the text part that has the input focus, which is the main text unless the user is editing a header, a footer or a text frame.

Combine the values of FindOptions with |:

ValueEffect
MatchCaseFinds only matches with the same uppercase and lowercase letters
MatchWholeWordFinds only whole words
ReverseSearches from the end of the document toward the beginning
NoHighlightDoesn't highlight the match
NoMessageBoxDoesn't show message boxes about the search result

Without NoMessageBox, the search can show message boxes to the user. Code that searches in a loop always sets it.

Replace All Occurrences

The following code in Form1.cs writes a sentence into the editor when the form opens, replaces every "order" with "purchase" and reports the number of replacements:

using System;
using System.Windows.Forms;
using TXTextControl;

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        Load += Form1_Load;
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        textControl1.Text = "Invoice for order 1234. Thank you for your order.";

        int count = ReplaceAll("order", "purchase");
        MessageBox.Show(count + " replacements");
    }

    private int ReplaceAll(string searchText, string replacementText)
    {
        FindOptions options = FindOptions.MatchWholeWord | FindOptions.NoMessageBox;
        int count = 0;

        // All replacements are undone in one step
        textControl1.BeginUndoAction("Replace All");

        try
        {
            int position = textControl1.Find(searchText, 0, options);

            while (position != -1)
            {
                textControl1.Select(position, searchText.Length);
                textControl1.Selection.Text = replacementText;
                count++;

                // Continue behind the inserted text
                position = textControl1.Find(searchText, position + replacementText.Length, options);
            }
        }
        finally
        {
            textControl1.EndUndoAction();
        }

        return count;
    }
}

Keep the namespace that Visual Studio created around the class. When the form opens, a message box reports 2 replacements, and the editor shows "Invoice for purchase 1234. Thank you for your purchase."

The code works as follows:

  • MatchWholeWord keeps "order" from matching inside longer words such as "orders". NoMessageBox keeps the search silent.
  • Select selects each match, and Selection.Text replaces it.
  • The next search starts behind the inserted text. A replacement that contains the search text, such as "order" replaced with "reorder", is not found again.
  • BeginUndoAction and EndUndoAction make the replacements one step, so a single Ctrl+Z restores the original text. See Undo and Redo.

Search Headers, Footers and Text Frames

TextControl.Find searches only the text part with the input focus. To search every part of a document, go through TextParts, which contains the main text, the headers and footers and the text frames. Each part is an IFormattedText object with its own Find method and Selection.

The following method highlights every occurrence of a text in yellow:

private void HighlightEverywhere(string searchText)
{
    foreach (IFormattedText textPart in textControl1.TextParts)
    {
        int position = textPart.Find(searchText, 0, FindOptions.NoMessageBox);

        while (position != -1)
        {
            textPart.Selection = new Selection(position, searchText.Length) { TextBackColor = System.Drawing.Color.Yellow };
            position = textPart.Find(searchText, position + searchText.Length, FindOptions.NoMessageBox);
        }
    }
}

For each match, a prepared Selection with TextBackColor colors the background of the found characters in that part.

Search With Regular Expressions

Find searches for literal text. For patterns such as dates, email addresses or invoice numbers, run a .NET regular expression over the text and select the matches by their positions. The blog article Advanced Smart Search with Regular Expressions in .NET C# shows an extension method that does this.

Next Steps