Validation Using the KeyPress Event in a Windows Application



Create a Windows application and design a form in it as per your requirements.

Now most of the time the user needs validation in a Windows application, so before the user enters a wrong value (such as instead of text the user enters an integer) we can validate it using an event and some sort of coding.

For example in the following screen, a KeyPress event is created for the TextBox.

KeyPress.gif

Now Create one Class Validation.cs and write the following code in it:

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)
        {
            try
            {
                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!");
                }
            }
            catch { }
        }

Now call these two methods as per validation type (char or int) from the TextBox KeyPress Event:

validation v = new validation();

  private void textBox5_KeyPress(object sender, KeyPressEventArgs e)
  {
       v.digitonly(e); // allowing interger only
  }

  private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
  {
       v.charonly(e);  // allowing character only
  }
  

Up Next
    Ebook Download
    View all
    Learn
    View all