Make a TextBox convert text into proper case in C#

The example Convert a string to proper case (title case) in C# uses a CultureInfo object's TextInfo property to convert text into proper case (or title case). There are a couple of tricks and potential problems that you need to know about if you want to use that technique to make a TextBox convert its contents to proper case.

One approach would be to intercept key strokes and convert the typed characters to create a proper case result. That's trickier than you might think. In particular, dealing with the user using Ctrl+X and Ctrl+V to cut or paste text in the TextBox is confusing.

Another strategy would be to catch the TextBox's TextChanged event and convert the text to proper case there. That event fires after text is cut or pasted so you have the final text easily available. That approach works but there's another issue to consider: where the user's focus is. After you change the text to proper case, you need to restore the focus to where it was before you changed the control's text.

This example uses the following TextChanged event handler to convert text into proper case.

// Convert the TextBox's text into proper case.
private void TextBoxToProperCase(TextBox txt)
{
    // Save the selection's start and length.
    int sel_start = txt.SelectionStart;
    int sel_length = txt.SelectionLength;

    CultureInfo culture_info = Thread.CurrentThread.CurrentCulture;
    TextInfo text_info = culture_info.TextInfo;
    txt.Text = text_info.ToTitleCase(txt.Text);

    // Restore the selection's start and length.
    txt.Select(sel_start, sel_length);
}

This code saves the TextBox's current selection position and length. It then converts the control's text to proper case and restores the original selection position and length.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.