# Search and Replace with the Selection object

Learn how to implement the search and replace functionality with the help of Selection object available in C1Editor for WinForms control.

## Content



Another common task for a text editor is search/replace functionality. The [C1Editor](/componentone/api/win/online-richtexteditor/dotnet-framework-api/C1.Win.C1Editor.4.8/C1.Win.C1Editor.C1Editor.html) has built-in commands for find and replace (implemented above using the [ShowDialog](/componentone/api/win/online-richtexteditor/dotnet-framework-api/C1.Win.C1Editor.4.8/C1.Win.C1Editor.C1Editor.ShowDialog.html) command), but in some cases you may want to implement this programmatically.

The code below shows how you can perform search and replace tasks using the **Selection** object:

DOC-DETAILS-TAG-OPEN

DOC-SUMMARY-TAG-OPEN

To write code in C#

DOC-SUMMARY-TAG-CLOSE

```csharp
void replaceUsingSelection_Click(object sender, EventArgs e)
{
    // strings to search and replace
    string search = "user";
    string replace = "customer";
    // do the work
    int count = 0;
    for (int start = 0; ; start += search.Length)
    {
        // get text (notice new line handling)
        string txt = this.c1Editor1.Text;
        txt = txt.Replace("\r\n", "\n");
        // find text, break when done
        start = txt.IndexOf(search, start, StringComparison.OrdinalIgnoreCase);
        if (start < 0)
        {
            break;
        }
        // select match
        this.c1Editor1.Select(start, search.Length);
        // replace text and make it bold
        this.c1Editor1.Selection.Text = replace;
        this.c1Editor1.Selection.ApplyTag("strong");
    }
    // done
    MessageBox.Show(string.Format("Done, {0} instances found.", count));
}
```

DOC-DETAILS-TAG-CLOSE

The code implements a loop that gets the editor's content as plain text and looks for a "search" string using the standard string.**IndexOf** method. When a match is found, the code selects the string using the [Select](/componentone/api/win/online-richtexteditor/dotnet-framework-api/C1.Win.C1Editor.4.8/C1.Win.C1Editor.C1Editor.Select.html) method and then replaces the text by modifying the **Text** property of the **Selection** object. As a bonus, the code also makes the replacement bold by applying the "strong" tag to the replacement text.

A good degree of compatibility with the familiar object model of the **TextBox** and **RichTextBox** classes is an important feature of the C1Editor.