简体   繁体   中英

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];
}

I got by using Keydown

private void tbxName_KeyDown(object sender, KeyEventArgs e)
    {
      
            if (tbxName.Text.Length == 0 || tbxName.SelectedText.Length == tbxName.Text.Length)
            {
                if ((e.Key >= Key.A) && (e.Key <= Key.Z))
                {
                    tbxName.Text = e.Key.ToString().ToUpper();
                    tbxName.SelectionStart = tbxName.Text.Length;
                    e.Handled = true;
                }
            }

            if (tbxName.Text.Length > 0)
            {
                int selectionStart = tbxName.SelectionStart;
                string character = tbxName.Text.Substring(selectionStart - 1, 1);

                if (character.Trim() == string.Empty)
                {
                    if ((e.Key >= Key.A) && (e.Key <= Key.Z))
                    {
                        tbxName.Text = tbxName.Text.Insert(selectionStart, e.Key.ToString().ToUpper());
                        tbxName.SelectionStart = selectionStart + 1;
                        e.Handled = true;
                    }
                }
            }

            if (e.Key == Key.Enter || e.Key == Key.Tab)
            {
                if (tbxName.Text.Length > 2)
                {
                    tbxDegree.Focus();
                    if (e.Key == Key.Tab)
                        e.Handled = true;
                }
                else
                {
                    MessageBox.Show("Kindly verify the Name Entered");
                    tbxName.Focus();
                }
            }
       
    }

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM