Working with Char in a RichTextBox

Posted Mon, Feb 22 2010 13:26 by Deborah Kurata

If you work with the RichTextBox control, you may find the need to work with individual characters within the control's text string.

The following demonstrates how to bold every uppercase character in a RichTextBox.

In C#:

richTextBox1.Text = "The ToCharArray function is very useful.";
char ch;
for (int i = 0; i <= richTextBox1.Text.Length - 1; i++)
{
    // Set the character
    ch = richTextBox1.Text[i];
    // Select the character
    richTextBox1.Select(i, 1);
    if (char.IsUpper(ch)) {
        richTextBox1.SelectionFont = new Font("Verdana", 14, FontStyle.Bold);
    }
    else {
        richTextBox1.SelectionFont = new Font("Arial", 12, FontStyle.Regular);
    }
}

In VB:

richTextBox1.Text = "The ToCharArray function is very useful.";
Dim ch As Char
For i As Integer = 0 To RichTextbox1.Text.Length - 1
    ' Set the character
    ch = RichTextbox1.Text(i)

    ' Select the character
    RichTextbox1.Select(i, 1)

    If Char.IsUpper(ch) Then
        RichTextbox1.SelectionFont = _
               New Font("Verdana", 14, FontStyle.Bold)
    Else
        RichTextbox1.SelectionFont = _
               New Font("Arial", 12, FontStyle.Regular)
    End If
Next

This code first sets some text into the RichTextBox. This is for testing purposes. In your application the data for the RichTextbox may come from the user or from a file.

The code then loops through each character in the RichTextBox text. It selects the character so that the SelectionFont can be used to set the font for the selected character.

The IsUpper method of the Char class determines whether the character is an upper case letter. If so, it sets a specific size, font, and bolds the character.

The result is as follows:

image

Enjoy!

Filed under: , , ,

Leave a Comment

(required) 
(required) 
(optional)
(required) 
If you can't read this number refresh your screen
Enter the numbers above: