Tuesday, August 26, 2008

Convert string to Title Case/Sentence Case in C#

The ToTitleCase method resides in the TextInfo class which is a member of the System.Globalization namespace. The ToTitleCase method is not static and needs an instance of the class.
To gain access to the TextInfo class you first have to specify cultural information which you can get from the CurrentCulture property of the thread the code is running on.

So:

using System.Globalization;
using System.Threading;

//Create CultureInfo and TextInfo classes to use ToTitleCase method
CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
TextInfo textInfo = cultureInfo.TextInfo;

oClient.ClientName = textInfo.ToTitleCase(txtClientName.Text);

Ps: Title Case converts every first letter of a word in a sentence to upper case, and the rest to lower case.

No comments: