How do I send different size strings from one RichTextBox to another?
I have a code that has chemical compounds that have a small font for the index. I currently have this code that transfers it from one RichTextBox
to the other when a button is clicked.
myRichTextBox.Text += otherRichTextBox.Text
As otherRichTextBox
I have a connection with different font sizes, but when I do, I end up in a string myRichTextBox
that does not store different font sizes and installs all of them in the font properties of the basic properties and size.
source to share
From the documentation at msdn:
"The Text property does not return any information about the formatting applied to the contents of the RichTextBox. To get rich text formatting (RTF) codes, use the Rtf property."
So, to assign a value using formatting, use this:
myRichTextBox.Rtf = otherRichTextBox.Rtf;
I replaced +=
with =
because I'm not sure if you wanted to add the value and not just replace it. If you are using +=
, you may run into problems because the "rtf" codes are added one after the other. However, try it ... you might not run into any problems at all.
source to share
To copy text, including formatting, you should use the normal RTB way:
- Make a choice and then act on it!
This is the way to go, no matter what you do:
- Customize the text with the
SelectionFont
,SelectionColor
,SelectionAlignment
etc. - Insert or remove text with
Cut
,Copy
orPaste
-
Find
text orAppendText
Here's how to do it:
otherRichTextBox.SelectionStart = 0; otherRichTextBox.SelectionLength = otherRichTextBox.Text.Length; myRichTextBox.AppendText(otherRichTextBox.SelectedText);
To insert a piece of text at a 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 the formatted text in pretty much any way !
A bit involved, but guaranteed to work correctly, as it does in the book.
To simply "clone" the full text, follow Grant's code:
myRichTextBox.Rtf = otherRichTextBox.Rtf;
It is possible to work with raw code Rtf
if you know what you are doing, but even though some things might still look fine, because some bugs and most layoffs are ignored, it has a tendency to collect crap. Therefore, you must follow the golden rule:
- Make a choice and then act on it!
Update: Here 's a good way to properly solve your problem with only two lines! (But you still have to live by the rule.)
source to share