How do I send varying text sized strings from one RichTextBox to another?

六眼飞鱼酱① 提交于 2019-12-02 10:18:14

From the documentation on msdn:

"The Text property does not return any information about the formatting applied to the contents of the RichTextBox. To get the rich text formatting (RTF) codes, use the Rtf property."

So to assign the value, with formatting, use this:

myRichTextBox.Rtf = otherRichTextBox.Rtf;

I've replaced += with = because I'm not sure you meant to append the value, rather than just replace it. If you do use +=, you may run into issues due to the "rtf" codes being appended one after the other. However, give it a try... you may not run into any issues at all.

TaW

To copy text including formatting you should use the usual RTB way:

  • Make a Selection and then act on it!

This is the way to go, no matter what you do:

  • Style your text with SelectionFont, SelectionColor, SelectionAlignment etc..
  • Insert or remove text with Cut, Copy or Paste
  • Find text or AppendText

Here is how to do what you asked about:

otherRichTextBox.SelectionStart = 0;
otherRichTextBox.SelectionLength = otherRichTextBox.Text.Length;
myRichTextBox.AppendText(otherRichTextBox.SelectedText);

To insert the portion of text at position n you write

otherRichTextBox.SelectionStart = 0;
otherRichTextBox.SelectionLength = otherRichTextBox.Text.Length;
myRichTextBox.SelectionStart = n;
myRichTextBox.SelectionLength  = 0;
myRichTextBox.SelectedText = otherRichTextBox.SelectedText;

You need to go by the rule anytime you want to change formatted text in pretty much any way!

A little bit involved but guaranteed to work correctly as it goes by the book.

To simply 'clone' the full text, go by Grant's code:

myRichTextBox.Rtf = otherRichTextBox.Rtf;

It is possible to work with the raw Rtf codes, if you know what you are doing, but even if some things may still look ok for a while because some errors and most redundancies get ignored, it has a tendency to collect crap.. So you should follow the golden rule:

  • Make a Selection and then act on it!

Update: Here is a nice way to solve your problem correctly with only two lines! (But you still need to live by the rule..)

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