-
Numbers Only
Hey,
i have made a program thats like a calculator, you type numbers into a text box and it does calculations. But the problem is you can still type letters into this text box, which confuses it.
i was wondering how you could make it so you can only enter numbers between 0-9 in the text box, and possibly make a pop say 'please enter number between 0-9' if you do press a letter.
thankyou
-
Re: Numbers Only
On the KeyPress event for the textbox you could check if anything other than numbers were entered and if so, pop up a box and then set the EventArg.Handled to True.
-
Re: Numbers Only
This is one of the most popular questions on the forum, so a search would turn up plenty of hits. It's quite easy to do half a job, which is what most of the advice people give will do. To do the full job is more difficult, particularly given that you would want to allow negatives and decimals. You would need to handle the KeyPress event and allow only the appropriate characters. Note though that the negative sign and decimal point are appropriate characters, but only one of each and only in certain positions.
-
Re: Numbers Only
Note also that just filtering characters does not prevent the user pasting whatever they like from the clipboard. Like I said, doing a full and proper job is more tedious than it would first appear. I'll tell you what I would do for a calculator. I wouldn't allow the user to enter anything into the TextBox directly. I'd have a button for each allowable character and use the form to catch KeyPresses, then call PerformClick on the appropriate Button when a valid key is pressed. There is also a NumberBox in the WFC library (see my signature for link). It's built for .NET 1.1 but I have tested it briefly and I think it works OK in 2.0 as well. There is also a 2.0 version on the way. It has been implemented to do the full job, preventing pasting illegal characters and all, plus you can configure it for different types of numbers. Not the best if you're trying to learn the ins and outs but great if it's the result that matters.