In VB6 there was a function called StrConv which we were using to convert a string to Proper Case or Title Case, but there is no direct equivalent in .NET. Yes, we can still use this function in vb.net but it's not a .NET way. I mean, StrConv cannot be used in C# directly. To use it in C# we need to add the reference of Microsoft.VisualBasic.Compatibility.dll. And people will not like to do so just to use a single function of that library.
Some people write their own function to achieve the functionality. They first convert all the letters of the string to lowercase and then loop through all the words and capitalize the first letter of each word of the string. I am not in favor of this approach. I don't like to write long code just to achieve a small functionality. I always look for shortcuts.
Though there is not direct equivalent for StrConv in .NET, .NET provides us System.Globalization.TextInfo class to overcome the problem. We can use ToTitleCase function of TextInfo class to convert the string in proper case.
I have written a small function to do the work.
EDIT: Please see the modified version of ToProperCase function in post #6 below.
vb.net Code:
Function ToProperCase( _
ByVal str As String _
) As String
Dim myTI As System.Globalization.TextInfo
myTI = New System.Globalization.CultureInfo("en-US", False).TextInfo
str = str.ToLower
str = myTI.ToTitleCase(str)
Return str
End Function
Usage:
vb.net Code:
Private Sub Button1_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs _
) Handles Button1.Click
MessageBox.Show(ToProperCase("HELLO WORLD!"))
End Sub
If you want to use ToProperCase() function like this...
Code:
Dim str As String = "HELLO WORLD!"
str = str.ToProperCase()
...then you need to use a concept called Extension Methods. Here it goes:
vb.net Code:
Module ExtensionMethods
<System.Runtime.CompilerServices.Extension()> _
Function ToProperCase( _
ByVal str As String _
) As String
Dim myTI As System.Globalization.TextInfo
myTI = New System.Globalization.CultureInfo("en-US", False).TextInfo
str = str.ToLower
str = myTI.ToTitleCase(str)
Return str
End Function
End Module