Textbox Validation using KeyPress Event in C#
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace KeyPressEvent { public partial class Form1 : Form { public Form1() { InitializeComponent(); txt_Mobile.MaxLength = 10; } private void txt_Name_KeyPress(object sender, KeyPressEventArgs e) { if (!char.IsLetter(e.KeyChar) && Convert.ToInt32(e.KeyChar) != 8) { errorProvider1.SetError(txt_Name, "Only letters allowed"); e.Handled = true; txt_Name.Focus(); } else { errorProvider1.Clear(); } } private void txt_Mobile_KeyPress(object sender, KeyPressEventArgs e) { if (!char.IsDigit(e.KeyChar) && Convert.ToInt32(e.KeyChar) != 8) { errorProvider1.SetError(txt_Mobile, "Only Numbers Allowed"); e.Handled = true; txt_Mobile.Focus(); } else { errorProvider1.Clear(); } } } } |
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
1 |
txt_Mobile.MaxLength = 10; |
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.
This is awesome!! really helpful for me. Thanks for sharing with us. Following links also helped me to complete my task.
http://www.mindstick.com/Blog/322/TextBox%20Validation%20in%20C%20Net
http://www.codeproject.com/Articles/220519/Numbers-or-Characters-only-Textbox-Validation-in-C