RichTextBox add some text in the middle of the text

对着背影说爱祢 提交于 2019-12-12 01:01:27

问题


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.



来源:https://stackoverflow.com/questions/15659995/richtextbox-add-some-text-in-the-middle-of-the-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!