当通过使用键盘(Tab、Shift+Tab 等)、通过调用 Select 或 SelectNextControl 方法或者通过将 ContainerControl ..::.ActiveControl 属性设置为当前窗体等方式更改焦点时,焦点事件按以下顺序发生:
Enter
GotFocus
Leave
Validating
Validated
LostFocus
当使用鼠标或通过调用 Focus 方法更改焦点时,焦点事件将按以下顺序发生:
Enter
GotFocus
LostFocus
Leave
Validating
Validated
如果 CausesValidation 属性设置为 false,则将取消 Validating 和 Validated 事件。
如果在 Validating 事件委托中, CancelEventArgs 的 Cancel 属性设置为 true,则正常情况下将在 Validating 事件之后发生的所有事件均被取消。
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 '[email protected]' "; return false; }
以上转自微软文档。
bof_.Code.controlBaseEdit.Validated+=new EventHandler(controlBaseEdit_CodeValidated);
bof_.Code.controlBaseEdit.Validating+=new CancelEventHandler(controlBaseEdit_CodeValidating);
void controlBaseEdit_CodeValidating(object sender, CancelEventArgs e)
{
if (IsEditing())
{
if (bof_.Code.controlBaseEdit.Text=="1")
{
bof_.Code.controlBaseEdit.Text = "Vadating";
}
}
}
1.有一个Save方法,
2.更改这一个TextBox的值为1(TextBox获得焦点)
3.点击Save键(当前焦点更改为在Save键)
4.上面事件Validating先发生,Text=="1",符合条件,TextBox值变为"Validating",执行Save事件保存TextBox值1到DB(更改焦点时发生事件,在控件正在验证时发生,微软上面例子,验证邮箱不能通过,添加错误消息)
5.接着发生Validated事件,TextBox值改为"validated"但是保存操作没有执行其更改的值。(在控件完成验证时发生,看上面微软例子,所有条件都符合时清除错误消息)
6.
2.从第2步重新开始,TextBox值改为2,(TextBox获得焦点)
3.
4.Text=="2",不符合Validating里再次更改TextBox值条件,所以Text还是“2”,保存"2"到DB
5.TextBox值更改为Validated.