5

I would like to know if there is a proper way for a textbox to accept only numbers.

For example, I want it to "stop" the user from filling it with "abcd1234" and only let him fill with "1234".

peterh
  • 11,875
  • 18
  • 85
  • 108
Mark Roll
  • 506
  • 3
  • 6
  • 15
  • When you say you want the string to stop the user from entering non-numerical characters are you then talking about a TextBox ? If not please add more information about this. – MrApnea Jun 14 '16 at 07:09
  • Yes Textbox, i update it now! – Mark Roll Jun 14 '16 at 07:10
  • 4
    Possible duplicate of [How do I make a textbox that only accepts numbers?](http://stackoverflow.com/questions/463299/how-do-i-make-a-textbox-that-only-accepts-numbers) – Mathias R. Jessen Jun 14 '16 at 07:13
  • 2
    first, what technology are you using? MVC, webpages, WPF, UWP, etc...? On the second hand, I'm guessing you map that to a property, so you should set that property to an `int`, and third, you can set your input to `type=number`(this works for web, not sure for WPF, UWP and others) and that will only allow numbers to be entered. – Spluf Jun 14 '16 at 07:19
  • Why don't you use a numericUpDown? Is better if you just want there to be numbers – Aimnox Jun 14 '16 at 08:47

3 Answers3

17

I tried following code and worked fine for me. The textbox will allow user to enter numbers only.

private void txtbox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar)) 
    {
        e.Handled = true;
    }
}

you can also try this

e.Handled = !(char.IsDigit(e.KeyChar));
Molx
  • 6,816
  • 2
  • 31
  • 47
sowjanya attaluri
  • 903
  • 2
  • 9
  • 27
0

You can evaluate the input using the following lines of code:

if (txtNumericBox.Text.All(char.IsDigit))
   // Proceed
else
   // Show error

If you define this as a string property with getter and setter then you can use like the following:

private string _MyNemericStringr;

public string MyNemericString
{
    get { return _MyNemericStringr; }
    set {
        if (value.All(char.IsDigit))
            _MyNemericStringr = value;
        else
            _MyNemericStringr = "0";
    }
}

In the second example, if you assign any non-digit value to the property then it will return the value as "0". otherwise it will process as usual.

sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
-1

you can try this simple code.

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

it only accept numeric values and Backspace

Ramgy Borja
  • 2,330
  • 2
  • 19
  • 40