Search code examples
c#keypress

How can i capitalize first letter of every word using keypress event with c#?


I must capitalize first letter of every word but with keypress event using C#. Right now every letter in the textbox gets capitalized, I added the code I use. I cant figure out how to capitalize just the first letter, or what am I doing wrong. Can you help me?

private void txt_name_KeyPress(object sender, KeyPressEventArgs e)
{
    e.KeyChar = (e.KeyChar.ToString()).ToUpper().ToCharArray()[0];
}

Solution

  • You will need to keep track of previous key presses if you must go this route:

    private char PreviousChar;
    
    private void txt_name_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (Char.IsWhiteSpace(PreviousChar) || PreviousChar == '\0')
        {
            e.KeyChar = Char.ToUpper(e.KeyChar);
        }
        PreviousChar = e.KeyChar;
    }