How to capitalize letter only in beginning of sentences, and the next word is normal

walk.this_way picture walk.this_way · Dec 31, 2013 · Viewed 28.8k times · Source

I use this:

Static PreviousLetter As Char
    If PreviousLetter = " "c Or TextBox1.Text.Length = 0 Then
        e.KeyChar = Char.ToUpper(e.KeyChar)
    End If
    PreviousLetter = e.KeyChar

But the result is always:

Good Night Every Body

How can I capitalize just the first letter in the sentence, leaving the other words normal? The result I want is:

Good night every body

Answer

Mike Dinescu picture Mike Dinescu · Dec 31, 2013

Don't use a static variable to hold the previous char. It's not needed and bad practice in general.

Then, although it's a bit unclear from your question, assuming you wish perform the change on the text of TextBox1, you will probably want to set the text back to the TextBox after changing it.

So a solution might looks like this:

 If TextBox1.TextLength > 1 Then
     TextBox1.Text = TextBox1.Text.Substring(0, 1).ToUpper() + TextBox1.Text.Substring(1)
 ElseIf TextBox1.TextLength = 1 Then
     TextBox1.Text = TextBox1.Text.ToUpper()
 EndIf

If you want to capitalize the first letter and force lowercase the rest you can modify the code above like so:

 If TextBox1.TextLength > 1 Then
     TextBox1.Text = TextBox1.Text.Substring(0, 1).ToUpper() + TextBox1.Text.Substring(1).ToLower()
 ElseIf TextBox1.TextLength = 1 Then
     TextBox1.Text = TextBox1.Text.ToUpper()
 EndIf

UPDATE

Based on the comments, if you want to make this change on the fly (ie. as the user is typing in the TextBox) then you will also need to manipulate the cursor. Essentially you need to store the cursor position prior to changing the text, and then restore the position after the change.

Also, I would perform these changes in the KeyUp event as opposed to the KeyPress event. The KeyUp happens after the TextBox has registered the change in response to the key press.

 Dim startPos as Integer
 Dim selectionLength as Integer

' store the cursor position and selection length prior to changing the text
 startPos = TextBox1.SelectionStart
 selectionLength = TextBox1.SelectionLength

 ' make the necessary changes
 If TextBox1.TextLength > 1 Then
     TextBox1.Text = TextBox1.Text.Substring(0, 1).ToUpper() + TextBox1.Text.Substring(1).ToLower()
 ElseIf TextBox1.TextLength = 1 Then
     TextBox1.Text = TextBox1.Text.ToUpper()
 EndIf

 ' restore the cursor position and text selection
 TextBox1.SelectionStart = startPos
 TextBox1.SelectionLength = selectionLength