简体   繁体   English

RichTextBox在文本中间添加一些文本

[英]RichTextBox add some text in the middle of the text

I have a RichTextBox and I want to add some text in the middle of the text . 我有一个RichTextBox ,我想在add some text middle add some text text For example I got this text: 例如,我得到了这个文字:

"FirstText SecondText" “FirstText SecondText”

I want to add some text between the "FirstText" and the "SecondText". 我想在"FirstText" and the "SecondText".之间添加一些文本"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. 我试图split the text to 2 strings并添加到第一个我的额外文本然后添加第二个字符串。 It worked but it is destroy my richTextBox1.SelectionColor (I got color...). 它工作但它破坏了我的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? 那么如何在不剪切我的richTextBox1.Text情况下添加文本或如何保存所有颜色数据呢?

You have to find the starting index yourself: 你必须自己找到起始索引:

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

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" 它将用“Good”一词替换你指定长度的文本中的任何位置

Check this post . 查看这篇文章

You might need to change the value of SelectionStart to the position where you want to put the new text. 您可能需要将SelectionStart的值更改为要放置新文本的位置。

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. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM