Keypress Event in C#

Key Press Event
 
This event fires or executes whenever a user presses a key in the TextBox.
 
You should understand some important points before we are entering into the actual example.
  1. e.Keychar is a property that stores the character pressed from the Keyboard. Whenever a key is pressed the character is stored under the e object in a property called Keychar and the character appears on the TextBox after the end of keypress event.
  2. e.Handled is a property then assigned to true, it deletes the character from the keychar property.
 
Indexof(): it returns the index number of the first occurence of the specified letter in the string.
 
Note: if the character doesn't exist in the string it returns -1.
 
Example 1:
 
Form8.cs[Design]
 
 
 
Form8.cs (Code Behind file) 
  1. private void textBox1_KeyPress(object sender, KeyPressEventArgs e)  
  2. {  
  3. string st = "0123456789"+(char)8;  
  4. if(st.IndexOf(e.KeyChar)==-1)  
  5. {  
  6. MessageBox.Show("please enter digits only");  
  7. e.Handled = true;  
  8. }  
  9. }  
Note:
 
The ASCII value of a Backspace is 8. In our keyboard, every key has an ASCII value, but it is very difficult to remember each and every ASCII value.
 
Microsoft has introduced a class called keys. By using this Key class you can easily determine the ASCII value.
 
Example 2

(The same example but I am using a predefind function.)
 
Microsoft provides a predifined function called IsDigit(). By using this function you can easily validate the data, whether a digit was entered or not. 
  1. private void textBox1_KeyPress(object sender, KeyPressEventArgs e)  
  2. {  
  3. if (!(Char.IsDigit(e.KeyChar) || (e.KeyChar == (char)Keys.Back)))  
  4. {  
  5. MessageBox.Show("please enter digits only");  
  6. e.Handled = true;  
  7. }  
  8. }  
Thank you.