# Search and Replace

> Open the Find and Replace dialog boxes and sidebars of a Windows Forms TextControl, call Find with FindOptions and replace all matches in one undo step.

- **Product:** TX Text Control .NET for Windows Forms
- **Section:** Documentation
- **Kind:** Topic
- **Path:** TX Text Control .NET for Windows Forms > Document Editor > Editing Text > Search and Replace
- **2734 words**
- **Web URL:** https://docs.textcontrol.com/tx-text-control-dotnet-winforms/document-editor/editing-text/search-replace/
- **LLMs URL:** https://docs.textcontrol.com/tx-text-control-dotnet-winforms/document-editor/editing-text/search-replace/llms.txt
- **LLMs-Full URL:** https://docs.textcontrol.com/tx-text-control-dotnet-winforms/document-editor/editing-text/search-replace/llms-full.txt

---

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](https://docs.textcontrol.com/tx-text-control-dotnet-winforms/getting-started/document-editor/first-application/llms-full.txt), whose editor is named `textControl1`. Selecting found text relies on the text positions explained on [Selections and Caret Position](https://docs.textcontrol.com/tx-text-control-dotnet-winforms/document-editor/editing-text/selections/llms-full.txt).

### 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](https://docs.textcontrol.com/tx-text-control-dotnet-winforms/reference/txtextcontrol/textcontrol/find-method/llms-full.txt) without parameters opens the built-in Find dialog box, and [Replace](https://docs.textcontrol.com/tx-text-control-dotnet-winforms/reference/txtextcontrol/textcontrol/replace-method/llms-full.txt) opens the Replace dialog box. Call them from any button or menu item of your form:

```csharp
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.](https://docs.textcontrol.com/assets/img/tx-text-control-dotnet-winforms/replace-dialog.958be617.webp)

The built-in keyboard assignment of the editor doesn't include Ctrl+F or Ctrl+H. [Keyboard Shortcuts](https://docs.textcontrol.com/tx-text-control-dotnet-winforms/document-editor/editing-text/keyboard-shortcuts/#add-your-own-shortcuts) shows how to add them.

#### Find and Replace in a Sidebar

A [Sidebar](https://docs.textcontrol.com/tx-text-control-dotnet-winforms/reference/txtextcontrol-windows-forms/sidebar/llms-full.txt) shows the same functions as a panel beside the document when its [ContentLayout](https://docs.textcontrol.com/tx-text-control-dotnet-winforms/reference/txtextcontrol-windows-forms/sidebar/contentlayout-property/llms-full.txt) is `Find` or `Replace`. Connected to the [FindSidebar](https://docs.textcontrol.com/tx-text-control-dotnet-winforms/reference/txtextcontrol-windows-forms-ribbon/ribbonformattingtab/findsidebar-property/llms-full.txt) and [ReplaceSidebar](https://docs.textcontrol.com/tx-text-control-dotnet-winforms/reference/txtextcontrol-windows-forms-ribbon/ribbonformattingtab/replacesidebar-property/llms-full.txt) properties of the `RibbonFormattingTab`, it opens when the user clicks **Find** or **Replace**; [Sidebar and Panels](https://docs.textcontrol.com/tx-text-control-dotnet-winforms/document-editor/ribbon-ui/sidebar/llms-full.txt) describes the setup.

### Find Text in Code

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

| Overload | Searches |
|---|---|
| `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](https://docs.textcontrol.com/tx-text-control-dotnet-winforms/reference/txtextcontrol/findoptions/enumeration/llms-full.txt) with `|`:

| Value | Effect |
|---|---|
| `MatchCase` | Finds only matches with the same uppercase and lowercase letters |
| `MatchWholeWord` | Finds only whole words |
| `Reverse` | Searches from the end of the document toward the beginning |
| `NoHighlight` | Doesn't highlight the match |
| `NoMessageBox` | Doesn'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:

```csharp
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](https://docs.textcontrol.com/tx-text-control-dotnet-winforms/reference/txtextcontrol/textcontrol/select-method/llms-full.txt) selects each match, and [Selection.Text](https://docs.textcontrol.com/tx-text-control-dotnet-winforms/reference/txtextcontrol/selection/text-property/llms-full.txt) 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](https://docs.textcontrol.com/tx-text-control-dotnet-winforms/reference/txtextcontrol/textcontrol/beginundoaction-method/llms-full.txt) and [EndUndoAction](https://docs.textcontrol.com/tx-text-control-dotnet-winforms/reference/txtextcontrol/textcontrol/endundoaction-method/llms-full.txt) make the replacements one step, so a single Ctrl+Z restores the original text. See [Undo and Redo](https://docs.textcontrol.com/tx-text-control-dotnet-winforms/document-editor/editing-text/undo-redo/llms-full.txt).

### 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](https://docs.textcontrol.com/tx-text-control-dotnet-winforms/reference/txtextcontrol/textcontrol/textparts-property/llms-full.txt), which contains the main text, the headers and footers and the text frames. Each part is an [IFormattedText](https://docs.textcontrol.com/tx-text-control-dotnet-winforms/reference/txtextcontrol/iformattedtext/llms-full.txt) object with its own [Find](https://docs.textcontrol.com/tx-text-control-dotnet-winforms/reference/txtextcontrol/iformattedtext/find-method/llms-full.txt) method and [Selection](https://docs.textcontrol.com/tx-text-control-dotnet-winforms/reference/txtextcontrol/iformattedtext/selection-property/llms-full.txt).

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

```csharp
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](https://docs.textcontrol.com/tx-text-control-dotnet-winforms/reference/txtextcontrol/selection/textbackcolor-property/llms-full.txt) 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#](https://www.textcontrol.com/blog/2025/01/29/advanced-smart-search-with-regular-expressions-in-net-csharp/) shows an extension method that does this.

### Next Steps

- [Undo and Redo](https://docs.textcontrol.com/tx-text-control-dotnet-winforms/document-editor/editing-text/undo-redo/llms-full.txt): group changes into one undo step.
- [Keyboard Shortcuts](https://docs.textcontrol.com/tx-text-control-dotnet-winforms/document-editor/editing-text/keyboard-shortcuts/llms-full.txt): assign Ctrl+F and Ctrl+H.
- [Built-in Dialog Boxes](https://docs.textcontrol.com/tx-text-control-dotnet-winforms/document-editor/ribbon-ui/dialog-boxes/llms-full.txt): the other dialog boxes of the editor.
- [Fields, Hyperlinks, and Bookmarks](https://docs.textcontrol.com/tx-text-control-dotnet-winforms/document-editor/fields/llms-full.txt): mark text that your code replaces later, instead of searching for it.

---

## Nearby

- **Previous:** [Undo and Redo](https://docs.textcontrol.com/tx-text-control-dotnet-winforms/document-editor/editing-text/undo-redo/llms-full.txt)
- **Next:** [Drag and Drop](https://docs.textcontrol.com/tx-text-control-dotnet-winforms/document-editor/editing-text/drag-drop/llms-full.txt)
