How to Use Multiple Color in RichTextBox using C#

By FoxLearn 12/2/2024 3:28:36 PM   4.88K
To use multiple colors in a RichTextBox in C#, you can use the SelectionColor property to change the color of the selected text.

When developing Windows Forms applications in C#, you may encounter scenarios where you need to display text in a RichTextBox with multiple colors.

Implementing Multiple Colors in RichTextBox in C#

Open Visual Studio, then click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "MultipleColorRichText" and then click OK

Drag and drop Label, TextBox, Button and RichTextBox controls from the Visual Toolbox onto your form designer, then design your form as shown below.

multiple color richtext

Add a ColorDialog to your form as below

color dialog in c#

Add code to handle your form

using System;
using System.Drawing;
using System.Windows.Forms;

namespace MultipleColorRichText
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        Color _color = Color.Blue; // Default text color
        bool _first = true;

        private void btnSend_Click(object sender, EventArgs e)
        {
            // Apply selected color to RichTextBox
            rtfResult.SelectionColor = _color;
            if (_first)
                rtfResult.SelectedText = txtValue.Text;
            else
                rtfResult.SelectedText = Environment.NewLine + txtValue.Text;
            _first = false;
            txtValue.Clear();
            txtValue.Focus();
        }

        private void pColor_Click(object sender, EventArgs e)
        {
            // Open color dialog and set selected color
            if (colorDialog1.ShowDialog() == DialogResult.OK)
            {
                _color = colorDialog1.Color;
                pColor.BackColor = _color;
            }
        }
    }
}

The RichTextBox control (rtfResult) is used to display the text. The SelectionColor property allows us to apply a specific color to the text being added.

A ColorDialog control enables users to pick a color dynamically. The pColor panel provides a visual indicator of the currently selected color.

When the Send button (btnSend) is clicked. The text in the input TextBox (txtValue) is added to the RichTextBox. Next, the selected color is applied using rtfResult.SelectionColor.

To ensure text entries appear on new lines after the first entry, the _first boolean flag determines whether to prepend a newline (Environment.NewLine) to the text.

This example illustrates how to add multi-colored text dynamically to a RichTextBox in a Windows Forms application.

VIDEO TUTORIAL