2017-07-19 52 views
0

我有它几个元素自定义用户控件,所以它看起来是这样的:按钮的单击事件验证文本框的事件之后从来没有发射被触发

UserControl 
    Textbox 
    Button 
    .... 

现在,如果我按一下按钮,像我在标题中提到,文本框将失去焦点,并且其验证事件将触发......但按钮的点击永远不会触发......我想这是一种常见的行为......但是,执行按钮的正确方法是什么?点击事件,如果验证没有失败?

这里是我使用的验证代码:

private void txtPassword_Validating(object sender, CancelEventArgs e) 
     { 
      string errorMessage = _uiValidator.ValidatePassword(txtPassword.Text); 

      errRegistration.SetError(txtPassword, errorMessage); 
     } 

所以errRegistration.SetError()已成功执行 - 的errorMessage为null,表示没有验证错误,所以我想这是很好(我查了这个通过放置一个断点)。

这是该按钮的Click事件的实现:

private void btnRegisterUser_Click(object sender, EventArgs e) 
    { 
     _uiValidator.ValidatePassword(txtUsername.Text); 
     //validate other fields here... 

     if (_uiValidator.IsValid()) 
     { 
      this._controller.Save(); 

     }else{ 
      MessageBox.Show("...", "Title", MessageBoxButtons.OK, MessageBoxIcon.Error); 
     } 
    } 
+0

文本框数据是否被绑定?如果你注释掉'_Validating'处理程序体,会发生什么?必须有一些取消事件(设置'e.Cancel'为'true') –

+0

数据未绑定...我手动填充文本框的文本值。我非常肯定我的代码中没有e.Cancel = true。 – Whirlwind

回答

0
private void btnRegisterUser_Click(object sender, System.EventArgs e) 
{ 
    foreach (Control control in this.Controls) 
    { 
     // Set focus on control 
     control.Focus(); 
     // Validate causes the control's Validating event to be fired, 
     // if CausesValidation is True 
     if (!Validate()) 
     { 
      DialogResult = DialogResult.None; 
      return; 
     } 
    } 
} 

尝试类似的东西。

+0

我用更多的代码更新了我的问题... – Whirlwind

+0

您是否尝试过输入会导致验证错误的数据,如果是这样,结果如何? – WabbitHunter

+0

查看我的更新代码,我想我明白你想要完成的。 Windows窗体需要比ASP.NET更多的验证编码。 – WabbitHunter

相关问题