C# RichTextBox Explained with Examples

1. Introduction to C# RichTextBox Control

Just like text box C# RichTextBox also a similar control, which takes text input in the form of ‘Rich Text’. What is the difference between typing a three-page document in notepad application and in WordPad application? Are you piling up with the differences? The difference that came in your mind is the difference between the ‘TextBox’ versus ‘RichTextBox’. This means unlike the typical Text box, in the RichTextBox we can mark the piece of the text and set unique aspects like bold, italic, text color, etc.

We can save and load the C# RichTextBox content into a physical disc in two formats. One is a ‘Plain Text (TXT format)’ format and the other one is ‘Rich Text Format (RTF format)’. In this article, we will have a look at the basic usage of the RichTextBox control.

2. About the C# RichTextBox Example

Below is the screenshot of the sample application for the example:

C# RichTextBox Control Example

C# RichTextBox Control Example

In this example, we can type the text content in the left-hand-side text area. Also, we can perform some basic operation on the typed content through the right-hand side Controls of the dialog.

2.1 Plain Text vs Rich Text

The control on the left-side of the dialog is called C# RichTextBox. This control supports Plain text and Rich Text. The Plain text will not have any property like bold text, text color or even configurable fonts with color and size. We may ask that the notepad is a utility supplied by windows that support plain text. But I can change the Font and Font Size. What we should know is that the Font or Font size is applied to the complete document and when we save plain text the change in the font not saved to the disc. That means plain text is still plain text. But the notepad (text viewer) applied the font change temporarily. If some other person opens the saved content from the disc, they may see a different text font their notepad configuration.

Rich text can hold a variety of properties with them. When you save the rich text, those properties also saved in the disc along with the text content. What property we are talking about? Well, it is like font colors, Italic, text size, etc. So whoever open the document, they see same text formatting.

2.2 Formatting Rich Text

We divide the sample into two panels. The left side panel has big RichTextBox Control for typing the text contents. Right side panel has three action buttons and using those we can perform various formatting operations on the typed content. We can save and load the document by clicking the corresponding button on the right-hand side action panel. We can change the text format by using the controls on section 2 of the panel. In this example, we can set Bold, Italic, Underline, Font and Font size to the text contents. But rich text supports much more such properties. We have picked those basic ones for demonstration. One can also try with formatting the text with colors.

2.3 Copy, Paste, Undo and Redo

The Normal text box supports copy and paste by default (Rich click on it). But rich text box does not provide that function by default. In section 3 of our Window Form, we can perform Copy and Paste clipboard operation. Also, here we can perform Undo and Redo actions.

Undo will dismiss the effect of our last operation. Say, for example, let us say, we did the following operation in a sequence on the Rich text content:

  1. Typed a some line of Texts
  2. Applied a Font for it
  3. Then Changed the Font Size

Now the two consecutive Undo will cancel the effect of Font and Font size in the rich text content. The Redo option will cancel the last Undo Operation.

3. Preparing the Form

We place two panels on the Form. We dock the first panel to the right of the Form and resized enough to support the buttons and other controls on the right. In our example, the RichTextBox occupies the full area on the left side. To do this, we place the C# RichTextBox Control in the left panel and set its Dock property to fill. Below are details:

  1. Form Place Holder for the two panels.
  2. Left Panel’s ‘Dock Property’ set to ‘Left’ and it holds all the action buttons.
  3. Right Panel’s dock property set to ‘Fill’ and holds only the RichTextBox control in it.
  4. RichTextBox is placed on the Right side panel, and its dock property is set to Fill.

Note that the Left-Side panel is filled in the remaining portion of the form. The remaining portion is the space left after housing the controls in the Right-Side Panel.  The RichTextBox fills the entire area of the Left Side Panel. The video in this section shows the form preparation.


Video Steps & Video

  1. First, we add a Panel to the form. Then, we dock it to the right-side edge of the form.
  2. Then the panel is resized.  The right-side panel will have all the command for the rich text box sample.
  3. Next we add one more panel to the left of the command panel.
  4. This panel is asked to fill the remaining area. Later we place the C# RichTextBox Control in it.

You can design form as shown in the above picture. To set properties, download the example at the end of this article and use it as reference.


4. Saving the C# RichTextBox Content

The ‘ <strong>SaveFile()</strong> Method’ of the C# RichTextBox control allows saving the RichTextBox content in two formats. One is plain text (.txt) and the other one is Rich text format (.rtf). We will pass the stream type to the above-said method specifying the format in which we want to save the data. Our example uses ‘ SaveFileDialog’ to pick a filename, and before displaying the dialog, we set the filter types to *.txt and *.rtf. Below is the code for saving RichTextBox data. The RichTextBox enumeration type ‘ RichTextBoxStreamType ’ is set to plain or rich based on the Filter type in the SaveFileDialog.

Below is the code:

The below video shows saving the Rich Text box content in a Plain text document.


Video Steps

  1. In the RichTextBox, first we type three lines of texts.
  2. Then we save the RichTextBox content in plain text format (.txt)
  3. We open the saved content with the notepad as it understands the plain text format.

5. Loading C# RichTextBox Content

The code implemented for loading the saved text looks like the event handler for save button click. Below are the exceptions.

  1. In place of using the SaveFileDialog, ‘Load Click Handler’ uses the OpenFileDialog.
  2. LoadFile() Method’ of the RichTextBox is called to load the file from the disc.

Below is the Code for loading the text file content.

Loading the already saved text content is shown in the below video.


Video Steps

  1. First, we Load the plain text content saved in the previous video.
  2. The video shows the loaded content in the RichTextBox control.

6. Set RichTextBox’s Bold, Italic, Underline Using SelectionFont

C# RichTextBox allows formatting the portion of the text in bold, Italic and Underlined. The capability of setting these kinds of attributes makes it different from the normal text box. Have a look at the below piece of code:

The code above changes the selected text to Bold style. First, we had taken the Font object of the selected text by making use of the ‘SelectionFont Property’ of the RichTextBox. Then a new font is constructed using the existing font returned by the SelectionFont property. During the construction, we used the Bit-wise XOR operation ( SelectedText_Font.Style ^ FontStyle.Bold) to negate the Bold style. This means if the selected font has bold property set, clicking the Bold button again will remove the Bold Style from the Font.

Below is the Full Code for Bold, Italic and Underline:

The below video shows how we apply bold and italic font style to specific text in the Rich Text:


Video Steps

  1. First, we load the text file from the disc.
  2. Next we apply bold, italic and underline style to some portion of the text.
  3. Then we save the result in Rich text format. (Note plain text won’t support text attributes for different portions of the text)
  4. Finally, we load the Rich Text content and check it shows text attributes applied in the previous step.

7. Setting RichTextBox Font Style and Size

It has more work to do. First, we should load the ‘System Fonts’ to a combo box shown in the sample app screen shot. Then we should load the ‘Font Sizes’ in another combo box.  Then regardless of whether user changed the combo box selection for Font or Font Size, we will re-construct the Font Object and set it to the selected text in the C# RichTextBox. Since both the combo boxes’ selection changed event does a similar job, we will write a custom function and call that for both the combo boxes.

7.1 Load Font Name in Combo Box

In the Form Load handler, we iterate the font families through the FontFamily Array returned by the ‘ GetFamilies()’ static method of ‘ FontFamily Class’. The method takes a Graphic object and we get the Graphics object linked to the RichTextBox by calling the function ‘ CreateGraphics()’. Once we have the Font Family name, we add the name to the Font Combo box. Below is the code for it:

Next, we populate the numeric values in the Font size ComboBox. Below is the code, which does not require any explanation:

7.2 Collect Selected Text’s Font Details

The ‘ SetNewFont’ function is written to change the font and font size of the selected text. Below is the Declaration required for the task:

We set the FSize variable with a more recent font size. To do that, we read the selected text from the font size ComboBox. When the user does not pick any font size from the ComboBox, we assign a default font size of 8. Also, we are storing the current font of the selected text in old_font.

Next, we store the font style and GDI Character Set from the existing font. The constructor of the Font class will use all the data we are collecting here. Below is the Code:

7.3 Set New Font

Now we have all data required for the new font. So, we construct the Font instance and set that instance as the current selection font. The Function ends here. Below is the code for it:

Note that all the information passed to the constructor is given a default value or collected from the existing font of the selected text. Finally, we call the SetNewFont function from ‘ SelectedIndexChanged Event’ Handler of both the Combo Boxes. Below is the code:

Below video shows setting different font and font size to a single line of text in RichTextBox control.


Video Steps

  1. First we loads already saved plain text.
  2. Then we select the second line of text.
  3. And applies different font and font style.
  4. Finally we save the content and reload it for a cross check.

8. Copy, Paste, Undo and Redo

C# RichTextBox gives all the functionality stated in the title as member functions. So the Click event handler on the form for tasks copy, paste, Undo and Redo will simply call the related member function of the C# RichTextBox. Below is the code:

Below video shows the clipboard operation on Rich Text. It also shows the use of undo and redo option on RichTextBox Control.


Video Steps

  1. The video copies #using statements from Source file.
  2. Then pastes the content to the rich text box.
  3. From the pasted content, copies some portion of text to clipboard.
  4. Opens the WordPad application and pastes it.
  5. Finally applied some attributes and shows the undo and redo options.

Source Code: Download the C# RichTextBox Example From Google Drive



Categories: C#

Tags: , , , , , , , , ,

Do you like this Example? Please comment about it for others!!

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: