Restricting users to input only numbers in C# windows application

You do not need to use a RegEx in order to test for digits:

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

To allow for backspace:

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

If you want to add other allowable keys, look at the Keys enumeration and use the approach above.


To allow only numbers in a textbox in a windows application, use

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

This sample code will allow entering numbers and backspace to delete previous entered text.


Use the Char.IsDigit Method (String, Int32) method and check out the NumericTextbox by Microsoft

MSDN How to: Create a Numeric Text Box

Tags:

C#

Winforms