Search code examples
c#keypress

Keypress exceptions on restricted characters


How can I allow the space bar to be used in a textbox that is restricted to numbers only?

 private void CLimitTxt_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (!char.IsNumber(e.KeyChar))
        {
            MessageBox.Show("You can only enter numbers within this textbox", "Error");
            CLimitTxt.Text = "";
            e.Handled = true;
        }
    }

Would I need to declare a var regex with an exception perhaps?


Solution

  • As simple as that:

    private void CLimitTxt_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (!char.IsNumber(e.KeyChar) && !e.KeyChar == ' ')
        {
            MessageBox.Show("You can only enter numbers within this textbox", "Error");
            CLimitTxt.Text = "";
            e.Handled = true;
        }
    }