Search code examples
c#winformsvalidationtextboxkeypress

Validate text box to limited numeric input


I have text box in c# windows form. Here I'm limiting the input of the tsextbox only to numeric values.

private void txtpref02_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!(Char.IsDigit(e.KeyChar)))
        e.Handled = true;
}

I have two other requirements.

  1. I want to enable the text box to accept only one digit. It should be 0,1,2 or 3.
  2. How to enable backspace in the code given above?

Solution

  • Here is how I'd do it:

    private void txtpref02_KeyDown(object sender, KeyEventArgs e)
    {
        switch(e.KeyCode)
        {
            case Keys.D0:
            case Keys.NumPad0:
            case Keys.D1:
            case Keys.NumPad1:
            case Keys.D2:
            case Keys.NumPad2:
            case Keys.D3:
            case Keys.NumPad3:
            case Keys.Back:
            case Keys.Delete:
                return;
            default:
                e.SuppressKeyPress = true;
                e.Handled = true;
                break;
        }
    }
    

    Also, you can set the MaxLength property to 1 to limit the number of characters as you've indicated.

    Please note: this code is using the KeyDown event, not the KeyPress event.