Textbox for Numeric Content in C# – Programming, Pseudocode Example, C# Programming Example
Windows Form WPF Form

Textbox for Numeric Content in C#

Sometimes it can make sense not to allow certain user input. For example, if you want to perform calculations on the contents of various text boxes, it is pointless to check if the content of each text box is actually a number.

Fortunately, text boxes have events that allow us to check an entered value before it appears in the text box. The event that matters to us is “KeyPress” and it is executed each time a character is typed into the text box, or more specifically, when a key is pressed. Finally, there are also keys that do not write characters.

If you want to react to the KeyPress event, the method looks like this:


While “sender” is of no interest to us, “e” contains the pressed key. In the past, you would have gone now and made different comparisons with the ASCII value of the pressed key. In the meantime it has become a bit easier.
But let’s first think about what we want exactly: We want to be able to enter numbers, but of course also keys like “Backspace” or the cursor keys have to work. It can happen that the user mistypes and wants to correct his input.

The result is surprisingly simple:


If the “KeyChar” of “e” is not a digit (number) nor a control (cursor key) then “Handled = true” should be. The property “Handled” indicates, literally translated, whether this keystroke has already been dealt with, ie was written to the text box. We manually set this property to prevent our input from appearing in the text box.

Of course, if you have a form with a lot of textboxes for numeric input only, it’s not terribly elegant for any of these textboxes to intercept the “KeyPress” event. In this case, we recommend a separate class for this type of textbox. Such a class is easily derivable from the base class. We just have to override a single method:


Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: