You are visiting wrong documentation page of MSDN. You should go through Button Events, there you can find help about Validated and Validating events.
Each Control
-derived object has two events named Validating
and
Validated
. Also it has a property called CausesValidation
.
When this is set to true (it is true by default) then the control
participates in validation. Otherwise, it does not.
Example:
private void textBox1_Validating(object sender,
System.ComponentModel.CancelEventArgs e)
{
string errorMsg;
if(!ValidEmailAddress(textBox1.Text, out errorMsg))
{
// Cancel the event and select the text to be corrected by the user.
e.Cancel = true;
textBox1.Select(0, textBox1.Text.Length);
// Set the ErrorProvider error with the text to display.
this.errorProvider1.SetError(textBox1, errorMsg);
}
}
private void textBox1_Validated(object sender, System.EventArgs e)
{
// If all conditions have been met, clear the ErrorProvider of errors.
errorProvider1.SetError(textBox1, "");
}
public bool ValidEmailAddress(string emailAddress, out string errorMessage)
{
// Confirm that the e-mail address string is not empty.
if(emailAddress.Length == 0)
{
errorMessage = "e-mail address is required.";
return false;
}
// Confirm that there is an "@" and a "." in the e-mail address, and in the correct order.
if(emailAddress.IndexOf("@") > -1)
{
if(emailAddress.IndexOf(".", emailAddress.IndexOf("@") ) > emailAddress.IndexOf("@") )
{
errorMessage = "";
return true;
}
}
errorMessage = "e-mail address must be valid e-mail address format.\n" +
"For example 'someone@example.com' ";
return false;
}
Edit:
Source:
The biggest problem with validation on WinForms is the validation is
only executed when the control has "lost focus". So the user has to
actually click inside a text box then click somewhere else for the
validation routine to execute. This is fine if your only concerned
about the data that is entered being correct. But this doesn't work
well if you're trying to make sure a user didn't leave a textbox empty
by skipping over it.
In my solution, when the user clicks the submit button for a form, I
check each control on the form (or whatever container is specified)
and use reflection to determine if a validating method is defined for
the control. If it is, the validation method is executed. If any of
the validations fail, the routine returns a failure and allows the
process to stop. This solution works well especially if you have
several forms to validate.
References:
WinForm UI Validation
C# Validating input for textbox on winforms