Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restricting users to input only numbers in C# windows application

Tags:

c#

winforms

I have tried this code to restrict only numbers.It type only numbers and don't make entry when we try to enter characters or any other controls, even it doesnt enter backspace also. how to prevent backspace from it.

private void TxtBox1_KeyPress(object sender, KeyPressEventArgs e)
{
     if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "\\d+"))
          e.Handled = true;
}
like image 614
Narayan Avatar asked Dec 21 '11 13:12

Narayan


3 Answers

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.

like image 153
Oded Avatar answered Oct 07 '22 20:10

Oded


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.

like image 33
Laxmikant Dange Avatar answered Oct 07 '22 22:10

Laxmikant Dange


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

MSDN How to: Create a Numeric Text Box

like image 37
dknaack Avatar answered Oct 07 '22 20:10

dknaack