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 backsp
you can use Char.IsDigit()
method
Use the Char.IsDigit Method (String, Int32) method and check out the NumericTextbox
by Microsoft
MSDN How to: Create a Numeric Text Box
put following code in keypress event of your textbox:
private void txtbox1_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar);
}
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.
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.
Methods Suggested above only prevent user typing anything but number, but it will fail if user copy and paste some text inside textbox so we also need to check the input on text change event
Create ontextchangeEvent
private void TxtBox1_textChanged(object sender, EventArgs e)
{
if (!IsDigitsOnly(contactText.Text))
{
contactText.Text = string.Empty;
}
}
private bool IsDigitsOnly(string str)
{
foreach (char c in str)
{
if (c < '0' || c > '9')
return false;
}
return true;
}