Wednesday, July 29, 2015

Visual Studio C# | Allow Integer Input Only


There are certain field that you only want the user to input integer or numbers but there is always that doubt that they will accidentally press a non-numeric characters.

The best way to catch that one is to forbid the user to input a letters, special characters and any other characters that is not needed for your specific field.

For example, you are doing a form for a product and part of it's fields is the 'Price'. We all know  that the price contains numbers and period ONLY.

Add a textfield on your form and named it 'txtPrice'.


Add the following code on your textfield's KeyPress event.



Explanation:

   e.KeyChar : This gets the current value of the key pressed in the keyboard.
   char.IsControl :  returns true if the user presses 'ctrl', 'alt' , etc.
   char.IsDigit : returns true if the user presses a number key.

Logic:

  If pressed key is NOT a control key AND NOT a digit AND NOT a period, then
  SET e.handled to true, which means to cancel the event or that your handling the event in your code instead.

 If pressed key is a period check if the textfields already contains a period, then
 don't let the characted to be pressed. (e.handled = true)


Sources:

  • http://www.homeandlearn.co.uk/csharp/csharp_s8p4.html
  • http://www.dotnetperls.com/char-isdigit
  • http://stackoverflow.com/questions/463299/how-do-i-make-a-textbox-that-only-accepts-numbers

0 comments:

Post a Comment