اعتبارسنجی TextBox با استفاده از رویداد KeyPress
ابتدا یک برنامه ویندوزی ایجاد کرده و دو TextBox بر روی آن قرار دهید:
سپس با راست کلیک رو نام پروژه در SolutionExplorer یک کلاس جدید با نام Validation ایجاد و کدهای زیر را به آن اضافه کنید :
using System; using System.Windows.Forms; namespace Validation { class Validation { public void charonly(KeyPressEventArgs e) { if (Char.IsNumber(e.KeyChar) || Char.IsSymbol(e.KeyChar) || Char.IsWhiteSpace(e.KeyChar) || Char.IsPunctuation(e.KeyChar)) { MessageBox.Show("Only Char are allowed"); e.Handled = true; } } public void digitonly(KeyPressEventArgs e) { if (!(char.IsDigit(e.KeyChar) || char.IsControl(e.KeyChar) || char.IsPunctuation(e.KeyChar))) { e.Handled = true; MessageBox.Show("Enter only digit and decimal point.", "Alert!"); } } } }
حال در رویداد KeyPerss مربوط به TextBox ها کدهای زیر را بنویسید :
using System.Windows.Forms; namespace Validation { public partial class Form1 : Form { public Form1() { InitializeComponent(); } Validation v = new Validation(); private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { v.digitonly(e); // allowing interger only } private void textBox2_KeyPress(object sender, KeyPressEventArgs e) { v.charonly(e); // allowing character only } } }
کدنویسی برنامه بالا طوری است که در TextBox اول فقط عدد و در دومی فقط حرف وارد شود. حال برنامه را اجرا کرده و با زدن عدد و حرف در هر دو TextBox نتیجه را مشاهده کنید.
اورفلو میکنه