Home > DeveloperSection > Articles > RichTextBox Control in C#.Net

RichTextBox Control in C#.Net


C# C# 
Ratings:
0 Comment(s)
 13325  View(s)
Rate this:

RichTextBox Control in C#.Net


The RichTextBox control enables text to be displayed with formatting in plain text or rich-text format (rtf). It also provides facility to save the text in file and restore from file.

Drag and drop RichTextBox control from toolbox on the window Form.

RichTextBox Control in C#.Net

Write the Text in RichTextBox

private void frmRichTextBox_Load(object sender, EventArgs e)

{

            // write text in RichTextBox

            richTextBox1.Text = "Hello How are you";

}

RichTextBox Control in C#.Net

Change ForeColor of text written in RichTextBox

In RichTextBox each text can be in different color.

Code:

private void frmRichTextBox_Load(object sender, EventArgs e)

        {

            //Find method is used to find the text written in RichTextBox

            richTextBox1.SelectionStart = richTextBox1.Find("Hello");

            richTextBox1.SelectionColor = Color.Red;

            richTextBox1.SelectionStart = richTextBox1.Find("How are you");

            richTextBox1.SelectionColor = Color.RoyalBlue;

         }

 Run the project

RichTextBox Control in C#.Net

Save RichTextBox Text into File and Restore from File

Code:

Write code in click event of button. When you double click on click event then click event handler will create in .cs file.

RichTextBox Control in C#.Net

private void btnSave_Click(object sender, EventArgs e)

{

     //SaveFile Method Saves the contents of the RichTextBox into a file

     richTextBox1.SaveFile("h1.rtf");

}

private void btnLoad_Click(object sender, EventArgs e)

{

  //LoadFile Method Loads the contents of a file into the RichTextBox control

     richTextBox2.LoadFile("h1.rtf");

}

RichTextBox Control in C#.Net

When you click save button then text written in RichTextBox1 will save to the specified file.

When you click Load button then contents of a specified file Load into the RichTextBox2.

RichTextBox Control in C#.Net


Don't want to miss updates? Please click the below button!

Follow MindStick