Make a TextBox convert text into proper case in C#

[proper case]

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 into 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 pressing Ctrl+X and Ctrl+V to cut or paste text in the TextBox is quite confusing.

Another strategy would be to catch the TextBox control’s TextChanged event and convert the text into 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 control’s current selection position and length. It then converts the control’s text to proper case and restores the original selection position and length. The result is quite good, although you still have the same drawbacks given by the CultureInfo object’s TextInfo property. In particular, it doesn’t handle some odd cases such as VBScript and O’Dell.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in controls, strings and tagged , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *