ShadyThGod ShadyThGod - 11 months ago 65 Question

Numbers And Special Characters Don't Work In Replace

I am trying to replace

in a RichTextBox. It replaces the text "a" not with "4" but with "4nsi4nsicpg1252ng16393rd4r"..

This is the code i'm using:
RichTextBox1.Rtf = RichTextBox1.Rtf.Replace("a", "4")

Any help on how I can replace an "a" with a "4"? BTW I can replace "a" with "test" but not "4"

Answer Source

RTF (Rich Text Format) is a mix of the text of your document and control words that describe how to format the text. The RichTextBox1.Rtf property returns RTF, not plain text, so your Replace statement is corrupting some of those RTF control words. For example, your RTF probably starts:

{\rtf1\ansi\ansicpg1252 ...

Where \rtf1, \ansi and \ansicpg1252 are RTF control words. Your Replace changed that to:

{\rtf1\4nsi\4nsicpg1252 ...

Since \4nsi and \4nsicpg1252 are no longer valid RTF control words, they end up being displayed as text - minus the \ character that is used to indicate the start of a control word.

The RichTextBox.Text property will return the plain text, so you could try using that instead, but I suspect that this would also strip out any formatting that had been applied to the document:

RichTextBox1.Text = RichTextBox1.Text.Replace("a", "4")