RichTextBox add some text in the middle of the tex

2019-08-22 04:39发布

问题:

I have a RichTextBox and I want to add some text in the middle of the text. For example I got this text:

"FirstText SecondText"

I want to add some text between the "FirstText" and the "SecondText". I have tried to split the text to 2 strings and add to the first my extra text then add him the second string. It worked but it is destroy my richTextBox1.SelectionColor (I got color...). So how can I add text without cutting my richTextBox1.Text or How can I save all the color data?

回答1:

You have to find the starting index yourself:

int index = richTextBox1.Text.IndexOf(" ");
if (index > -1) {
  richTextBox1.Select(index, 1);
  richTextBox1.SelectedText = " Inserted Text ";
}


回答2:

Are you familiar with the starting position and ending positions ? you could simply do something like this

richTextBox1.SelectionStart = index;
richTextBox1.SelectionLength = length;//you need to assign an integer where to start
richTextBox1.SelectedText =  "Good"; 

it will replace whatever position in text where you have assigned length with the word "Good"



回答3:

Check this post.

You might need to change the value of SelectionStart to the position where you want to put the new text.

In case you need to find the correct index, you can use something like this:

    startIndex = richTextBox1.Find(expressionToFind, 0,
                            richTextBox1.Text.Length,
                            RichTextBoxFinds.WholeWord);

Hope it helps.