In this post we will see the textbox validation using KeyPress Event in Windows C# . For this i am taking two textboxes on a form one is  txt_Name and another is  txt_Mobile . 

And i am taking one error provider on form. The Form designed as shown in figure below.

keypress-event-winforms-1
Now the C# code is like this.

In the above code we have written keypress events for both the textboxes txt_Name and txt_Mobile .

Keypress Event for txt_Name is to validate Textbox so that it should allow only characters . otherwise errorProvider shows a error with a message “Only letters allowed ” .

Keypress Event for txt_Mobile is to validate Textbox so that it should allow only Numbers . otherwise errorProvider shows a error with a message “Only Numbers allowed ” .

We can fix the maximum lenth of the txt_Mobile to 10. you can see the line of code


And the code

Convert.ToInt32(e.KeyChar) != 8

is to accept back space in a textbox . if this line of code is not present, textbox wont allow backspace also.

1 thought on “Textbox Validation using KeyPress Event in C#”

Leave a Reply

Your email address will not be published. Required fields are marked *