Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better Way of Manipulating RichText in C#?

Tags:

string

c#

rtf

I need to create and copy to the clipboard some RichText with standard "formatting" like bold/italics, indents and the like. The way I'm doing it now seems kind of inelegant... I'm creating a RichTextBox item and applying my formatting through that like so:

RichTextBox rtb = new RichTextBox();
Font boldfont = new Font("Times New Roman", 10, FontStyle.Bold);
rtb.Text = "sometext";
rtb.SelectAll()
rtb.SelectionFont = boldfont;
rtb.SelectionIndent = 12;

There has got to be a better way, but after a few hours of searching I was unable to come up with anything better. Any ideas?

Edit: The RichTextBox (rtb) is not displayed/drawn anywhere on a form. I'm just using the object to format my RichText.

like image 703
BKimmel Avatar asked Sep 25 '08 21:09

BKimmel


People also ask

When should we use RichTextBox?

A RichTextBox is a better choice when it is necessary for the user to edit formatted text, images, tables, or other rich content. For example, editing a document, article, or blog that requires formatting, images, etc is best accomplished using a RichTextBox.

How do I add text to RichTextBox?

Step 2: Drag the RichTextBox control from the ToolBox and drop it on the windows form. You are allowed to place a RichTextBox control anywhere on the windows form according to your need. Step 3: After drag and drop you will go to the properties of the RichTextBox control to add text in the RichTextBox control.

How do you save a rich text format in a database?

You can store rich, formatted text in an Access database by using a Long Text (also called Memo) field and setting the field's TextFormat property to RichText. For example, you can make the text bold or underlined, apply different fonts to individual words or characters, and change text colors.


2 Answers

You may want to suspend the layout of the richtextbox before you do all of that, to avoid unecessary flicker. That's one of the common mistakes I used to make which made it seem "inelegant"

like image 159
hova Avatar answered Sep 29 '22 02:09

hova


I think your technique is a great way to accomplish what you're looking to do. I know what you mean...it feels kind of "dirty" because you're using a Winforms control for something other than it was intended for, but it just works. I've used this technique for years. Interested to see if anyone else has viable options.

like image 43
jwalkerjr Avatar answered Sep 29 '22 01:09

jwalkerjr