How To Use Validation In Windows Form Application

Here are the steps: 

Step 1: Create a Windows form application.
 


Step 2:
Choose “ErrorProvider” form toolbox.



Step 3:
Select the Text box and go to its properties.



In properties choose “Events” and under focus double click on “validating”.

Now we have the text box validation method.

  1. private void textBoxName_Validating(object sender, CancelEventArgs e)   
  2. {  
  3.     if (string.IsNullOrWhiteSpace(textBoxName.Text))   
  4.     {  
  5.         e.Cancel = true;  
  6.         textBoxName.Focus();  
  7.         errorProviderApp.SetError(textBoxName, "Name should not be left blank!");  
  8.     } else   
  9.     {  
  10.         e.Cancel = false;  
  11.         errorProviderApp.SetError(textBoxName, "");  
  12.     }  

 

Step 4: Now validation should be triggered on Enter key press. Add following code to Enter key click method.
  1. private void buttonEnter_Click(object sender, EventArgs e)  
  2. {  
  3.     if (ValidateChildren(ValidationConstraints.Enabled))   
  4.     {  
  5.         MessageBox.Show(textBoxName.Text, "Demo App - Message!");  
  6.     }  
  7. }   
Also make sure that Enter button's "CauseValidation" property should be set to "true".

Now our window form in ready with validation.