RichTextBox control is only using first formatting

722 views Asked by At

I am using Visual Studio 10, .NET Framework 4 and was creating a Rich Text Box Control for Text Input. I am formatting text ONLY by writing the

*RichTextBox*.SelectionFont = new Font(currentFontFamily, currentFontSize, currentFontStyle);

Method.

When I am now accessing the Rtf formatted String via the RichTextBox.Rtf property, it works, but ONLY contains the first formatting.

For example:

Hello World

results in:

{\rtf1\ansi\ansicpg1252\deff0\deflang1031{\fonttbl{\f0\fnil\fcharset0 Verdana;}}
{\colortbl ;\red0\green0\blue0;}
\viewkind4\uc1\pard\cf1\b\f0\fs18 Hello World\par
}

which actually is Hello World

This is the same for everything. Fonts, Sizes, Colors, Formatting and so on. Can anyone help??

2

There are 2 answers

3
Stefan Wanitzek On BEST ANSWER

This is propably because the properties SelectionStart and SelectionLength are not valid. If you explicit limit the selection via those properties the RTF-output will be as expected:

richTextBox1.Text = "Hello World";

// limit selection
richTextBox1.SelectionStart = 0;
richTextBox1.SelectionLength = 5;

richTextBox1.SelectionFont = new Font("Tahoma", 12, FontStyle.Bold);

MessageBox.Show(richTextBox1.Rtf);

becomes

{\rtf1\ansi\deff0{\fonttbl{\f0\fnil\fcharset0 Tahoma;}{\f1\fnil\fcharset0 Microsoft Sans Serif;}}
\viewkind4\uc1\pard\lang1031\b\f0\fs24 Hello\b0\f1\fs17  World\par
}

Edit:

As the asker mentioned below the real cause of the problem was a call to TrimEnd():

richTextBox1.Text.TrimEnd()

As soon as he removed it everything worked as expected.

0
Tom On

I found out the problem.

*RichTextBox*.Text = *RichTextBox*.Text.TrimEnd();

causes the Rtf to lose some of its formatting. I thought it would have only had an influence on the text itself, not the formatting (especially when just removing whitespace characters) - I guess I was wrong.

Thanks again viertausend for the help