Today, I’ve come across of a requirement within a windows application to suppress the user input and allow only integers for a text box. Currently am working with .net framework 4.0 and I use C# as programming language. Before I search the web for any code samples, MSDN is my primary source for understanding the control behavior as well as the different events that are associated. In most cases MSDN would have proper help text and meaningful examples.
For my requirement, eliminate user input if it is other than integer, I found a link from MSDN.
The given example is inappropriate for eliminating the key input. The given example doesn’t work for you, if your interest is to prevent the user to input anything other than the numbers. I’ve tried and came up with a simple workout for preventing the user to input other than numbers. Here is my code, please comment and revise if it can be more simplified.
Step 1: We need a small reusable function as mentioned below.
bool IsDigitInput(char keyValue)
return ((keyValue >= '0') && (keyValue <= '9') || keyValue.Equals('\b'));
Step 2: Consume the above method at the KeyPress event of the text box as mentioned below
e.KeyChar = new char();