Deborah's Developer MindScape

         Tips and Techniques for Web and .NET developers.

February 22, 2010

Working with Char in a RichTextBox

Filed under: C#,VB.NET @ 3:26 pm

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)
        RichTextbox1.SelectionFont = _
               New Font("Arial", 12, FontStyle.Regular)
    End If

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:



1 Comment

  1.   Rahul Chowdhury — February 15, 2013 @ 1:04 pm    Reply

    Thanks, I was looking for this for a long time, and finally found a helpful article.

RSS feed for comments on this post. TrackBack URI

Leave a comment

© 2019 Deborah's Developer MindScape   Provided by WPMU DEV -The WordPress Experts   Hosted by Microsoft MVPs