Assuming the
Control.CausesValidation Property (System.Windows.Forms)[
^] is set to true:
The Validating event happens when the user tries to move away from a control, immediately after the Leave event, and allows you to cancel the attempt to leave if your validation fails by setting the Cancel property of the supplied CancelEventArgs. It you set Cancel to true, the focus will not move away from the control.
The Validated event happens immediately after the Validating event - provided it doesn't set the Cancel property - and allows you to work with the validated data.
private void tbSolution_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
TextBox tb = sender as TextBox;
if (tb != null)
{
e.Cancel = !tb.Text.StartsWith("A");
}
}
private void tbSolution_Validated(object sender, EventArgs e)
{
TextBox tb = sender as TextBox;
if (tb != null)
{
Console.WriteLine("{0} is OK!", tb.Text);
}
}
The text will only be printed provided it starts with the letter 'A'