Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Team Foundation Server Hosting
Search :       Advanced Search »
Home » Windows Controls C# » RichTextBox in C#

RichTextBox in C#

A RichTextBox control is an advanced text box that provides text editing and advanced formatting features including loading rich text format (RTF) files. In this article, I will demonstrate how to create and use various features of Windows Forms RichTextBox control.

Author Rank :
Page Views : 38356
Downloads : 498
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
RichTextBoxSampleCSharp.zip
 
 
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


RichTextBox Control
A RichTextBox control is an advanced text box that provides text editing and advanced formatting features including loading rich text format (RTF) files.
In this article, I will demonstrates how to create and use various features of the Windows Forms RichTextBox control.

Creating a RichTextBox

We can create a RichTextBox control using a Forms designer at design-time or using the RichTextBox class in code at run-time.

To create a RichTextBox control at design-time, you simply drag and drop a RichTextBox control from the Toolbox onto a Form in Visual Studio. Once a RichTextBox is added to a Form, you can move it around and resize it using the mouse and set it's properties and events.

Creating a RichTextBox control at run-time is merely a work of creating an instance of RichTextBox class, setting it's properties and adding the RichTextBox object to the Form's Controls collection.

The first step to create a dynamic RichTextBox is to create an instance of the RichTextBox class. The following code snippet creates a RichTextBox control object.

// Create a RichTextBox object

RichTextBox dynamicRichTextBox = new RichTextBox();

 

In the next step, you may set properties of a RichTextBox control. The following code snippet sets size, location, background color, foreground color, Text, Name, and Font properties of a RichTextBox.

dynamicRichTextBox.Location = new Point(20, 20);

dynamicRichTextBox.Width = 300;

dynamicRichTextBox.Height = 200;

// Set background and foreground

dynamicRichTextBox.BackColor = Color.Red;

dynamicRichTextBox.ForeColor = Color.Blue;

 

dynamicRichTextBox.Text = "I am Dynamic RichTextBox";

dynamicRichTextBox.Name = "DynamicRichTextBox";

dynamicRichTextBox.Font = new Font("Georgia", 16);

 

Once a RichTextBox control is ready with its properties, the next step is to add the RichTextBox control to the Form. To do so, we use Form.Controls.Add method. The following code snippet adds a RichTextBox control to the current Form.

 

Controls.Add(dynamicRichTextBox); 

 

A RichTextBox control looks like Figure 1.

RTBImg1.jpg

Figure 1

Setting RichTextBox Properties

After you place a RichTextBox control on a Form, the next step is to set properties.

The easiest way to set properties is from the Properties Window. You can open Properties window by pressing F4 or right click on a control and select Properties menu item. The Properties window looks like Figure 2.

RTBImg2.jpg

Figure 2

Location, Height, Width, and Size

The Location property takes a Point that specifies the starting position of the RichTextBox on a Form. The Size property specifies the size of the control. We can also use Width and Height property instead of Size property. The following code snippet sets Location, Width, and Height properties of a RichTextBox control.

dynamicRichTextBox.Location = new Point(20, 20);

dynamicRichTextBox.Width = 300;

dynamicRichTextBox.Height = 200;

Background, Foreground, BorderStyle

BackColor and ForeColor properties are used to set the background and foreground color of a RichTextBox respectively. If you click on these properties in Properties window, the Color Dialog pops up.

Alternatively, you can set background and foreground colors at run-time. The following code snippet sets BackColor and ForeColor properties.

// Set background and foreground

dynamicRichTextBox.BackColor = Color.Red;

dynamicRichTextBox.ForeColor = Color.Blue;

 

You can also set the borders style of a RichTextBox by using the BorderStyle property. The BorderStyle property is represented by a BorderStyle enumeration that has three values – FixedSingle, Fixed3D, and None.  The default value of border style is Fixed3D. The following code snippet sets the border style of a RichTextBox to FixedSingle.

dynamicRichTextBox.BorderStyle = BorderStyle.FixedSingle;

Name

The Name property represents a unique name of a RichTextBox control. It is used to access the control in the code. The following code snippet sets and gets the name and text of a RichTextBox control.

dynamicRichTextBox.Name = "DynamicRichTextBox";

Text and TextLength

The Text property of a RichTextBox represents the current text of a RichTextBox control. The TextLength property returns the length of a RichTextBox contents.

The following code snippet sets the Text and TextAlign properties and gets the size of a RichTextBox control.

dynamicRichTextBox.Text = "I am Dynamic RichTextBox";

int size = dynamicRichTextBox.TextLength;

Append Text

One way to append text to a RichTextBox is simply set Text property to current text plus new text you would want to append something like this.

RichTextBox1.Text += " Appended text";

RichTextBox also has the ApendText method to do the same. The AppendText method appends text at the end of a RichTextBox. The following code snippet uses AppendText method to append text to the RichTextBox1 contents.

RichTextBox1.AppendText(" Appended text");

AcceptsTab

If a RichTextBox control is set to multiline, the AcceptsTab property is used to set the RichTextBox control to accept the TAB key as text. If this property is not set, pressing the TAB key simply moves to the next control on the Form. By default, the AcceptsTab property value of a RichTextBox control is false.

// accepts TAB key

dynamicRichTextBox.AcceptsTab = true;

WordWrap

If WordWrap property is true, the text in the RichTextBox control automatically wraps to the next line if required. If this property is set to true, horizontal scroll bars are not displayed regardless of the ScrollBars property setting.

 

// Wordwrap

dynamicRichTextBox.WordWrap = true;

ScrollBars

A Multiline RichTextBox control can have scrollbars. The ScrollBars property of RichTextBox control is used to show scrollbars on a control. The ScrollBars property is represented by a RichTextBoxScrollBars enumeration that has four values – Both, Vertical, Horizontal, and None.

The following code snippet makes both vertical and horizontal scrollbars active on a RichTextBox control and they will be visible when the scrolling is needed on a RichTextBox control.

dynamicRichTextBox.ScrollBars = RichTextBoxScrollBars.Both;

Font

Font property represents the font of text of a RichTextBox control. If you click on the Font property in the Properties window, you will see Font name, size and other font options. The following code snippet sets Font property at run-time.

dynamicRichTextBox.Font = new Font("Georgia", 16);

Maximum Length

You can restrict the number of characters in a RichTextBox control by setting MaxLength property. The following code snippet sets the maximum length of a RichTextBox to 50 characters.

dynamicRichTextBox.ReadOnly = true;

dynamicRichTextBox.MaxLength = 50;

ReadOnly

You can make a RichTextBox control read-only (non-editable) by setting the ReadOnly property to true. The following code snippet sets the ReadOnly property to true. 

dynamicRichTextBox.ReadOnly = true;

Enabling and Disabling Shortcuts

ShortcutsEnabled property of the RichTextBox is used to enable or disable shortcuts. By default, shortcuts are enabled. The following code snippet disables shortcuts in a RichTextBox.

dynamicRichTextBox.ShortcutsEnabled = false;

ShortcutsEnabled property applies to the following shortcut key combinations:

  • CTRL+Z
  • CTRL+E
  • CTRL+C
  • CTRL+Y
  • CTRL+X
  • CTRL+BACKSPACE
  • CTRL+V
  • CTRL+DELETE
  • CTRL+A
  • SHIFT+DELETE
  • CTRL+L
  • SHIFT+INSERT
  • CTRL+R

Read RichTextBox Contents

The simplest way of reading a RichTextBox control contents is using the Text property. Note however that the Text property has no formatting; it has only text. See the Rtf property for the text including the formatting. The following code snippet reads contents of a RichTextBox in a string.

string RichTextBoxContents = dynamicRichTextBox.Text;

In a multiline RichTextBox, if the RichTextBox contents are separated by multiple lines and you want to read contents of a RichTextBox line by line, you can use the Lines property of the RichTextBox. The Lines property returns an array of strings where each element of the returned array is a line.

The following code snippet reads a RichTextBox contents line by line.

string [] RichTextBoxLines = dynamicRichTextBox.Lines;

foreach (string line in RichTextBoxLines)

{

    MessageBox.Show(line);

}

Selection in RichTextBox

The SelectedText property returns the selected text in a RichTextBox control.

string selectedText = dynamicRichTextBox.SelectedText;

You may also use SelectionStart and SelectionLength properties to get and set the selected text in a RichTextBox. The SelectionStart property represents the starting index of the selected text and SelectionLength property represents the number of characters to be selected after the starting character. The following code snippet sets the selection on a RichTextBox.   

dynamicRichTextBox.SelectionStart = 10;

dynamicRichTextBox.SelectionLength = 20;

 

Clear, SelectAll and DeselectAll

The Clear method removes the contents of a RichTextBox. The following code snippet uses Clear method to clear the contents of a RichTextBox. 

RichTextBox1.Clear();

RichTextBox class provides SelectAll and DeselectAll methods to select and deselect all text of a RichTextBox control. The following code snippet shows how to use SelectAll and DeselectAll methods.

private void selectAllToolStripMenuItem_Click(object sender, EventArgs e)

{

    if (RichTextBox1.TextLength > 0)

        RichTextBox1.SelectAll();

}

 

private void deselectAllToolStripMenuItem_Click(object sender, EventArgs e)

{

    if (RichTextBox1.TextLength > 0)

        RichTextBox1.DeselectAll();

}     

Cut, Copy, Paste, Undo Operations in RichTextBox

RichTextBox class provides Cut, Copy, Paste, and Undo methods to cut, copy, paste, and undo clipboard operations. The following code snippet shows how to use Cut, Copy, Paste, and Undo methods.

private void cutToolStripMenuItem_Click(object sender, EventArgs e)

{

    if (RichTextBox1.SelectionLength > 0)

        RichTextBox1.Cut();  

}

 

private void copyToolStripMenuItem_Click(object sender, EventArgs e)

{

        if (RichTextBox1.SelectionLength > 0)

            RichTextBox1.Copy();           

}

 

private void pasteToolStripMenuItem_Click(object sender, EventArgs e)

{

    if (Clipboard.GetDataObject().GetDataPresent(DataFormats.Text))

    {

            RichTextBox1.Paste();

    }

}

 

private void undoToolStripMenuItem_Click(object sender, EventArgs e)

{

    if (RichTextBox1.CanUndo)

    {

        RichTextBox1.Undo();

        RichTextBox1.ClearUndo();

    }           

}

Load and Save RTF Files

LoadFile method of RichTextBox control is used to load an RTF file and displays its contents. SaveFile method is used to save the contents of a RichTextBox to an RTF file. The following code snippet loads an RTF file using an OpenFileDialog and saves back its contents.

private void LoadRTFButton_Click(object sender, EventArgs e)

{

    OpenFileDialog ofd = new OpenFileDialog();

    ofd.InitialDirectory = "c:\\";

    ofd.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";

    ofd.FilterIndex = 2;

    ofd.RestoreDirectory = true;

 

    if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)

    {

        dynamicRichTextBox.LoadFile(ofd.FileName);

        dynamicRichTextBox.Find("Text", RichTextBoxFinds.MatchCase);

 

        dynamicRichTextBox.SelectionFont = new Font("Verdana", 12, FontStyle.Bold);

        dynamicRichTextBox.SelectionColor = Color.Red;

 

        dynamicRichTextBox.SaveFile(@"C:\Junk\SavedRTF.rtf", RichTextBoxStreamType.RichText);

    }

}

 

BulletIndent

BulletIndent property gets or sets the indentation used in the RichTextBox control when the bullet style is applied to the text.

dynamicRichTextBox.BulletIndent = 10;

Selection Properties

Here is a list of properties that are applicable on current selected text.

  • <!--[if !supportLists]-->SelectionAlignment – Alignment of selected text.
  • <!--[if !supportLists]--> <!--[endif]-->SelectionBackColor – Background color of selected text.
  • <!--[if !supportLists]--> <!--[endif]-->SelectionBullet – True or false to set if bullets are applied on selected text.
  • <!--[if !supportLists]--> <!--[endif]-->SelectionCharOffset - Whether text in the control appears on the baseline, as a superscript, or as a subscript below the baseline
  • <!--[if !supportLists]--> <!--[endif]-->SelectionColor – Color of selected text.
  • <!--[if !supportLists]-->SelectionFont – Font of selected text.
  • <!--[if !supportLists]--><!--[endif]-->SelectionHangingIndent - Distance between the left edge of the first line of text in the selected paragraph and the left edge of subsequent lines in the same paragraph.
  • <!--[if !supportLists]-->SelectionIndent - Length, in pixels, of the indentation of the line where the selection starts.
  • <!--[if !supportLists]--><!--[endif]-->SelectionProtected - Calue indicating whether the current text selection is protected
  • <!--[if !supportLists]-->SelectionTabs - Absolute tab stop positions.
  • <!--[if !supportLists]-->SelectionType – Selection type represented by RichTextBoxSelectionType enumeration with values Empty, Text, Object, MultiChar, and MultiObject.

The following code snippet sets these selection properties.

private void SelectionButton_Click(object sender, EventArgs e)

{

    dynamicRichTextBox.BackColor = Color.White;

    dynamicRichTextBox.Clear();

 

    dynamicRichTextBox.BulletIndent = 10;

    dynamicRichTextBox.SelectionFont = new Font("Georgia", 16, FontStyle.Bold);

    dynamicRichTextBox.SelectedText = "Mindcracker Network \n";

    dynamicRichTextBox.SelectionFont = new Font("Verdana", 12);

    dynamicRichTextBox.SelectionBullet = true;

    dynamicRichTextBox.SelectionColor = Color.DarkBlue;

    dynamicRichTextBox.SelectedText = "C# Corner" + "\n";

    dynamicRichTextBox.SelectionFont = new Font("Verdana", 12);

    dynamicRichTextBox.SelectionColor = Color.Orange;

    dynamicRichTextBox.SelectedText = "VB.NET Heaven" + "\n";

    dynamicRichTextBox.SelectionFont = new Font("Verdana", 12);

    dynamicRichTextBox.SelectionColor = Color.Green;

    dynamicRichTextBox.SelectedText = ".Longhorn Corner" + "\n";

    dynamicRichTextBox.SelectionColor = Color.Red;

    dynamicRichTextBox.SelectedText = ".NET Heaven" + "\n";

    dynamicRichTextBox.SelectionBullet = false;

    dynamicRichTextBox.SelectionFont = new Font("Tahoma", 10);

    dynamicRichTextBox.SelectionColor = Color.Black;

    dynamicRichTextBox.SelectedText = "This is a list of Mindcracker Network websites.\n";

}

The output text in a RichTextBox looks like Figure .

Redo and CanRedo

Redo method can be used to reapply the last undo operation to the control.

CanRedo property represents whether there are actions that have occurred within the RichTextBox that can be reapplied.

if (dynamicRichTextBox.CanRedo == true)

{

    if (dynamicRichTextBox.RedoActionName != "Delete")

        dynamicRichTextBox.Redo();

}

DetectUrls

If set true, the DetectUrls property will automatically format a Uniform Resource Locator (URL) when it is typed into the control.

EnableAutoDragDrop

RichTextBox control supports drag and drop operations that allow us to drag and drop text, picture, and other data. EnableAutoDragDrop property enables drag-and-drop operations on text, pictures, and other data.

dynamicRichTextBox.EnableAutoDragDrop = true;

RightMargin, AutoWordSelection, and ZoomFactor

RightMargin property represents the size of a single line of text within a RichTextBox control.

AutoWordSelection property represents if a word is automatically selected when a text is double clicked within a RichTextBox control.

ZoomFactor represents the current zoom level of the RichTextBox. Value 1.0 means there is no zoom applied on a control.

private void ZoomButton_Click(object sender, EventArgs e)

{

    dynamicRichTextBox.AutoWordSelection = true;

    dynamicRichTextBox.RightMargin = 5;

    dynamicRichTextBox.ZoomFactor = 3.0f;

}

Rtf and SelectedRtf

Rtf property is used to get and set rich text format (RTF) text in a RichTextBox control. SelectedRtf property is used to get and set selected text in a control. RTF text is the text that includes formatting. 

Summary
A RichTextBox control accepts user input on a Form and provides rich text features. In this article, we discussed discuss how to create a RichTextBox control in Windows Forms at design-time as well as run-time. After that, we saw how to use various properties and methods.

Further Readings
Here is a list of more articles related to this topic.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Mahesh Chand
Mahesh is the founder of C# Corner and Mindcracker Network, an author of several .NET programming books and a Microsoft MVP for 6 consecutive years. In his day to day work, Mahesh is a Senior Software Consultant with over 14 years of IT industry experience building systems for Financial and Banking, Engineering & Architectural, Imaging, Construction, Biological & Pharmaceuticals, Healthcare and Education industries. His expertise is Windows Forms, ASP.NET, Silverlight, WPF, WCF, Visual Studio 2010, SQL Server, and Oracle.  If you are looking for a Sharepoint, Windows Forms, ASP.NET, WPF, Silverlight, C#, VB.NET, Oracle, and SQL Server Consultant in Philadelphia area or remote location, drop me a line at MAHESH [AT] C-SHARPCORNER [DOT] COM.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Comments
Post comment or questions by Mahesh On August 29, 2010
here
Reply | Email | Modify 
Multi richtextbox with multi tab by Tanmay On August 30, 2010
Sir, I get a problem, I dynamicaly build a tab with richtextbox. & want to save it. but i can't save that. Can you help me please?

my code is as follows,

int counter=0;
        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TabPage tp = new TabPage();
            this.tabControl1.Controls.Add(tp);
            RichTextBox rt = new RichTextBox();
            rt.Dock = System.Windows.Forms.DockStyle.Fill;
            counter++;
            tp.Name = "New Doc "+Convert.ToString(counter);
            tp.Text = "New Doc " + Convert.ToString(counter);
            tp.Controls.Add(rt);
        }

I think we can get the selected tab like,

tabControl1.SelectedTab.Name

but how get the richtextbox to save the content.

Thank you!
Reply | Email | Modify 
well formated Display in RichTextBox in c# by Astika On December 25, 2010
I want to display the question & mark in One RichText Box.but they Apper as Qno.1Attempt All marks=[2] Qno2:Attempt Any One of the Foolwing mark=[9] but i want it as Qno.1Attempt All marks=[2] Qno2:Attempt Any One of the Foolwing mark=[9] so have can i do it. i want to digive space in the Question And Marks.please Replay me. Thanks
Reply | Email | Modify 
m ur fan sir.......good by Muhammad On March 12, 2011
m belongin to AJK University pakistan and std of sftware engineering ....in a class i cant understand that wt lectrs delever by prof but u r a great u teach me properly and this site is bcom a helper....now m going to develop a last project in uni ...but in this section i need a help....i think u can......... kindly tell me when u online? fm93.usman@yahoo.com same on facebook u can search me....BBye...n love u
Reply | Email | Modify 
Re: m ur fan sir.......good by Mahesh On March 12, 2011
You probably want to post all of your questions on the forums. I usually am busy and do not have much time to talk direct.
Reply | Email | Modify 
6 Months Free & No Setup Fees ASP.NET Hosting!
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.