0

I have a custom user control with few elements in it, so it looks like this:

UserControl
   Textbox
   Button
   ....

Now if I click the button, like I mentioned in the title, textbox will loose the focus, and its Validating event will fire...But button's click will never fire... I guess this is an usual behaviour...But what is the proper way, to execute button's Click event if validation didn't fail ?

Here is the code I use for validation:

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

            errRegistration.SetError(txtPassword, errorMessage);
        }

So errRegistration.SetError() has been executed succesfully - errorMessage is null, means no validation errors, so I guess that is fine (I checked this by putting a breakpoint).

And this is the button's Click event implementation:

    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);
       }   
    }
4

1 回答 1

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;
        }
    }
}

尝试类似的东西。

于 2017-07-19T14:55:31.327 回答