Search code examples
c#event-handlingkeypress

TextBox Keypress Event Validation


I would like to have a validation on my text box based the users input (keypress event). I have set the max length of my text box to 3 characters. The first character entered by the user should be a character (from a-z) and then the two succeeding characters must be a number. Backspace is allowed. So far I have this code but does not work as I would want to..

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            countChar = this.textBox1.Text;
            if (String.IsNullOrEmpty(this.textBox1.Text))
            {
                e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back);
            }
            else if (countChar.Length == 1)
            {
                e.Handled = e.KeyChar == (char)Keys.Back;
            }
            else if (countChar.Length == 2 || countChar.Length == 3)
            {
                e.Handled = e.KeyChar >= '0' && e.KeyChar <= '9' || e.KeyChar == (char)8;
            }
    }

Any suggestions?


Solution

  • This should work

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            countChar = this.textBox1.Text;
    
            if (String.IsNullOrEmpty(this.textBox1.Text))
            {
                e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back);
            }
            else if (countChar.Length == 1 || countChar.Length == 2)
            {
                e.Handled = !(char.IsDigit(e.KeyChar) || e.KeyChar == (char)Keys.Back);
            }
            else if (countChar.Length == 3)
            {
                e.Handled = e.KeyChar != (char)Keys.Back;
            }
            else
            {
                e.Handled = true;
            }
        }