views:

50

answers:

1

Hey guys,

Perhaps I'm missing something real simple here, but I've been struggling to change the RTF property of my RichTextBox in order to apply some color coding to my text. Probably the most straight-forward example of the problem I'm having is setting the Rtf property to include a color table in its header.

The default RTF string returned by the Rtf property:

{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset0 Microsoft Sans Serif;}}\viewkind4\uc1\pard\f0\fs17\par}

And the new RTF string I'd like to set with my color table:

{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset0 Microsoft Sans Serif;}{\colortbl;\red128\green0\blue0;\red0\green128\blue0;\red0\green0\blue255;}}\viewkind4\uc1\pard\f0\fs17\par}

And I set this using:

RichTextBox richTextBox = new RichTextBox();
richTextBox.Rtf = rtfStr; // My new RTF string, as seen above.

However, via debugger, it can be observed the that Rtf property stubbornly refuses to change; no exceptions are thrown, it just refuses to change. Same issue happens when I string.Replace() words to include RTF color tags around them. I've also tried turning off any ReadOnly properties on the text box.

Any suggestions would be most helpful, thanks!

  • Dave
A: 

Why not use the built in functionality to change color?

    rtbPreview.SelectionStart = 1;
    rtbPreview.SelectionLength = 3;
    rtbPreview.SelectionFont = newFont;
    rtbPreview.SelectionColor = Color.Red;

Or, if you really need to mess with the RTF format, set the color programmatically, then see what RTF it generates, and give that a try. Maybe the format is not correct so it is silently squelching an error.

Edit: Also, I hope you are not actually creating a new RTB every time. If you are, it looks from your sample that you're not adding it to the controls collection in which case it will never be seen anyways.

Jeremy
Well, I definitely see what you are seeing. It looks like the RichTextBox control tries to "fix" your RTF for you by adding thing and deleting things as it deems fit. When I set the color as above, take that RTF, and feeed it back in, it is just fine. If I feed it something slightly different, it deletes my color table. If I give it no text, it also seems to delete the color table, presumably because there is no text to color.
Jeremy
Very interesting. I've noticed some sort of "self-correcting" behavior in terms of the RTF property. I've also checked the "bad format, silent correction" theory by giving it a blatantly bad RTF string, which it immediately rejects with an ArgumentException.To address your concern, my RTB is part of a Windows Form, so it is not being recreated, and is in fact being displayed.
Dave