Mark Roll
Mark Roll

Reputation: 566

How can I make a TextBox accepts only numeric values?

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".

Upvotes: 5

Views: 49945

Answers (3)

sowjanya attaluri
sowjanya attaluri

Reputation: 911

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));

Upvotes: 18

Ramgy Borja
Ramgy Borja

Reputation: 2458

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

Upvotes: -1

sujith karivelil
sujith karivelil

Reputation: 29036

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.

Upvotes: 0

Related Questions