.netCoders Contact Us
Search:

Validation

Validating and Validated Events

There are two events associated with the validation of windows controls. The first, Validating, occurs while the control is validation. The second, Validated, occurs after the control is validated. Focus events occur in the following order:
  1. Enter
  2. GotFocus
  3. Leave
  4. Validating
  5. Validated
  6. LostFocus
The signatures for these two events are as follows. Note that the Validating event has a CancelEventArgs parameter, while the Validated event takes an EventArgs parameter. If you set the Cancel property of the Validating event's CancelEventArgs parameter to true, this indicates that the field failed validation. Hence, the Validated event will not fire.
private void textBox2_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
    //Run custom validation
    if (RunValidationCheck(textBox2.Text) == false)
    {
        // Set the ErrorProvider error with the text to display.
        this.errorProvider1.SetError(textBox2, "Invalid name");

        //If the Cancel property is set to true, the validation stops and the Validated event does not fire.
        e.Cancel = true;
    }
}

private void textBox2_Validated(object sender, System.EventArgs e)
{
    //Textbox validated, so clear any error messages.
    errorProvider1.SetError(textBox2, "");
}
Remember, the Validating event is where you run your validation, and indicated any error messages. The Validated event happens after successful validation, and allows you to clear any error messages.

ErrorProvider

The ErrorProvider control is used to indicate invalid data on a data entry form. Using this control, you can attach error messages that display next to the control when the data is invalid, as seen in the following image. A red circle with an exclamation point blinks, and when the user mouses over the icon, the error message is displayed as a tooltip.

First, drop the ErrorProvider control onto your form. Since it is not a UI element, it shows up in the tray at at the bottom of the form. To set an error message on a control, call the ErrorProvider's SetError method, passing in the object name (eg. textbox1) and the message to display. The following code is used behind the scenes in the above screenshot:
errorProvider1.SetError(textBox2, "Invalid name");
This code can be used in the Validating event, described in the previous section.