Search code examples
c#winformsmasking

Masking a textbox for Numbers only but wont accept BackSpace


I have a textbox that I would like for only numbers. But if I hit the wrong number, I cant backspace to correct it. How can I allow backspaces to work. Thanks

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

Solution

  • You could add a check to allow control characters as well:

    if (Char.IsControl(e.KeyChar) != true && Char.IsNumber(e.KeyChar) != true)
    {
        e.Handled = true;
    }
    

    Update: in response to person-b's comment on the code s/he suggests the following style (which is also how I would personally write this):

    if (!Char.IsControl(e.KeyChar) && !Char.IsNumber(e.KeyChar))
    {
        e.Handled = true;
    }