ChathurawinD
ChathurawinD

Reputation: 784

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?

Upvotes: 1

Views: 755

Answers (2)

rory.ap
rory.ap

Reputation: 35260

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.

Upvotes: 3

dario
dario

Reputation: 5259

Try this:

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

To accept only one character, you can use the MaxLength property of the TextBox.

Upvotes: 0

Related Questions