How do I make a textbox that only accepts numbers?

I have a windows forms app with a textbox control that I want to only accept integer values. In the past I’ve done this kind of validation by overloading the KeyPress event and just removing characters which didn’t fit the specification. I’ve looked at the MaskedTextBox control but I’d like a more general solution that could work with perhaps a regular expression, or depend on the values of other controls.

Ideally this would behave such that pressing a non numeric character would either produce no result or immediately provide the user with feedback about the invalid character.

40 s
40

Leave a Comment