Creating an XHTML Editor in Code > Performing Other Common Tasks > Search and Replace with the Selection object |
Another common task for a text editor is search/replace functionality. The C1Editor has built-in commands for find and replace (implemented above using the ShowDialog 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:
To write code in C#
C# |
Copy Code
|
---|---|
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)); } |
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 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.