Tuesday 1 April 2014

Why to make a TextBox numeric ?
  
Imagine the situation in which you are making a calculator app and if the user types chars except digits that may result in undesired output. A wise programmer will not let that happen and he will restrict the user to type only numbers so that the chance of user mistyping is eliminated. 
     
    Today i am going to tell you how to make numeric textbox and other useful stuff you can do with textbox
    Here is the code :


  private void textBox1_KeyPress(object sender, KeyPressEventArgs e)   
    {   
     if (!(e.KeyChar >= 48 && e.KeyChar <= 57 && e.KeyChar != 8))   
      e.Handled = true;   
    }   

     "textBox1_KeyPress" method is called every time a key is pressed inside the "textBox1". Inside the method there is an if which checks  weather or not ASCII key Code of the key pressed by the user is greater or equal to 48 and less than or equal to 57 if both the conditions becomes true then the corresponding character appears in the "textBox1" if not then the "keyEvent" is cancelled. KeyEvent is cancelled by setting "e.Handled = true;".

 You can restrict your textbox to accept only the keys you want it to accept for this you need to know  ASCII values for keyboard keys.
  If you don't know the ASCII values for keyboard keys you can check them HERE

 There is another method for doing this which is a bit easier for beginners :

  private void textBox1_KeyPress(object sender, KeyPressEventArgs e)   
    {   
     if (!char.IsDigit(e.KeyChar) && e.KeyChar != 8)   
      e.Handled = true;   
    }  

   In this case whenever the user presses the key C# checks weather or not the key pressed by the user represents a digit if the key represents a digit the key event goes fine but if not then the key event is cancelled. The other thing you have to do is to enable the backspace button by using its ASCII value.



 
Other useful textbox Properties

You can make your textbox secure by using the PasswordChar property you can set the PasswordChar to any char and when you type in the textbox the digits are hidden and password char is diplayed instead. This is useful in many situations for example if you are creating the facebook login app you don't want anyone to see what you typed in password textbox.

You can set the maximum length of the characters the textbox accepts by setting textbox.MaxLength.

 If you want some different text color in the textbox you can use textbox.ForeColor property and you can do the same for Background as well. See which colors C# supports HERE.

Hope you Liked this FOLLOW Me for more!!!

0 comments:

Post a Comment

Subscribe to RSS Feed Follow me on Twitter!