Saturday, February 12, 2011

RichTextBox.SelectedRtf property has incomplete documentation

The Microsoft documentation for this property is missing critical information (there's a shock, huh?). It explains use of the property in terms of text. It's not text that is being used here, it is a completely formatted document. That document is extracted from or integrated into the complete document stored within the RichTextBox control.

If used to insert text, the assigned string must be a correctly-formatted RTF document (even a minimal document will work) or it will throw a System.ArgumentException error, with the unhelpful inner message of "File format is not valid", especially maddening when not working with files.

To illustrate an incorrect and correct use of this property, in the example code snippets below, myRtfControl is an instance of the RtfTextBox control.

Example that fails:

myRtfControl.Select(myRtfControl.TextLength, 0); // Set caret to append

text.myRtfControl.SelectedRtf = "\ul underlined text\ul0";

// ^ Throws System.ArgumentException


Example that works:

myRtfControl.Select(myRtfControl.TextLength, 0); // Set caret to append

text.myRtfControl.SelectedRtf = "{\rtf1\ul underlined text\ul0}";

// ^ Adds underlined text as expected.


Note that for an empty selection, SelectedRtf actually contains the following document:

{\rtf1\ansi\ansicpg1252\deff0\deflang1033\uc1 }


The text consists of a single Unicode space character "\uc1 ". It's this "empty" document that assignment will replace.

Gathering this information came at the expense of several days of wasted time poring through tangential examples on the web (and some peeled wall paint from cursing bad documentation). Thanks to those intrepid pioneers.

For further reference, a link to the Rich Text Format Specification, version 1.6 can be found at http://msdn.microsoft.com/en-us/library/aa140277%28office.10%29.aspx.

Happy document bug hunting!

1 comment:

  1. Very handy! Found this through a Google search, of course. Looks like it's time to brush up on the RTF specs in all my many free minutes. Thanks for this!

    ReplyDelete