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.
- private void textBoxName_Validating(object sender, CancelEventArgs e)
- {
- if (string.IsNullOrWhiteSpace(textBoxName.Text))
- {
- e.Cancel = true;
- textBoxName.Focus();
- errorProviderApp.SetError(textBoxName, "Name should not be left blank!");
- } else
- {
- e.Cancel = false;
- errorProviderApp.SetError(textBoxName, "");
- }
- }
Step 4: Now validation should be triggered on Enter key press. Add following code to Enter key click method.
- private void buttonEnter_Click(object sender, EventArgs e)
- {
- if (ValidateChildren(ValidationConstraints.Enabled))
- {
- MessageBox.Show(textBoxName.Text, "Demo App - Message!");
- }
- }
Also make sure that Enter button's "CauseValidation" property should be set to "true".
Now our window form in ready with validation.