Prevent user input for Number / Chars / etc

 

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

if (!IsDigitInput(e.KeyChar))
{
e.KeyChar = new char();
}

Comments

Popular posts from this blog

Network Intrusion Detection using Supervised ML technique

Common mistakes by Interviewer

Keep the system active, to avoid the auto lock