Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
3.33/5 (3 votes)
See more:
Hello Guys,

Is there a way to restrict users to input only numbers in TextBox control?

I can use the TextChanged Event handler and remove any character other than numbers but is there an easier way to do it?

Your help is highly appreciated.

Thanks,
Posted

If you are using multiple numeric text boxes you can build your own control[^].
 
Share this answer
 
I made one a while ago that may be of use - here[^].

It is a NumericTextBox rather than a NumberTextBox as it still treats the input as a string, no decimal point and no - sign.
 
Share this answer
 
Try using a NumericUpDown instead. Maybe it will do the job for you.
 
Share this answer
 
Rather than rolling your own logic, you could always use a masked edit box. It makes sense to use something that's been written for you rather than you having to try and manage it yourself.
 
Share this answer
 
Comments
Dalek Dave 16-May-10 19:39pm    
I suggested something similar a few weeks ago, so Good answer :)
Genius.Boy wrote:
Is there a way to restrict users to input only numbers in TextBox control


Yes their is a way....

all u have to do is copy paste this piece of code in the key press event of your textbox where u want only numbers to appear and you are done, now lets say you are validating for mobile numbers then

private void txtmobile_KeyPress(object sender, KeyPressEventArgs e)
        {
//only number code
            if (char.IsNumber(e.KeyChar) == false)
            {
                e.Handled = true;
            }
//backspace working code
            if (e.KeyChar == (char)Keys.Back)
            {
                e.Handled = false;
            }
        }


do rate my answer once you find it useful

Thanks & regards
Radix :rose:
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900