简体   繁体   English

更改文本框焦点时,停止触发验证事件

[英]Stop validation event from firing, when changing textbox focus

I'm having a problem with validation on texbox components, in a winforms c# project. 我在winforms c#项目中对texbox组件进行验证时遇到问题。

I have several textboxes in a "Create product" form, which validates numbers, empty strings ect. 我在“创建产品”表单中有几个文本框,用于验证数字,空字符串等。 If i go from one textbox (with validation) to another, the validation event fires, and i cannot change focus, ie im stuck at the textbox, until i type something. 如果我从一个带有验证的文本框转到另一个文本框,则触发验证事件,并且我无法更改焦点,即,我停留在文本框上,直到我键入某些内容为止。 The behaviour i was looking for, should fire the validation events on the textboxes when i hit a "Create button", and not when i change focus from one textbox to another. 我一直在寻找的行为,应该在我点击“创建按钮”时触发文本框上的验证事件,而不是当我将焦点从一个文本框更改为另一个文本框时触发。

Any hints, or good practice as how to solve this? 有什么提示或良好做法,如何解决呢? Much appreciated.. 非常感激..

Current code: 当前代码:

//Validation event for one of the textboxes. epProductName is an ErrorProvider:
private void txtProductName_Validating(object sender, CancelEventArgs e)
    {
        if (Validator.IsEmpty(txtProductName))
        {
            epProductName.SetError(txtProductName, "Field must not be empty");
            e.Cancel = true;
        }
        else
        {
            epProductName.Clear();
        }
    }

//Submit button click event
private void btnSubmit_Click(object sender, EventArgs e)
    {
        if (ValidateChildren())
        {
            try
            {
                SelectedProduct.ImagePath = txtChoosePicture.Text;
                SelectedProduct.InstructionPath = txtChooseManual.Text;
                SelectedProduct.SheetPath = txtChooseDatasheet.Text;
                SelectedProduct.IsDeleted = false;
                SelectedProduct.ProductNameNum = txtProductName.Text;
                SelectedProduct.Description = txtProductDescription.Text;
                SelectedProduct.DaysToExpire = int.Parse(txtUseTime.Text);
                SelectedProduct.Category_Id = (int)cbChooseCategory.SelectedValue;

                int productId = pm.CreateProduct(SelectedProduct);

                MessageBox.Show("New Product: Id: " + productId + ", Product name: " + SelectedProduct.ProductNameNum, "New product created",
                                     MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);

                this.Dispose();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Product was not created. Details: " + ex.Message, "Error",
                                 MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
            }
        }
    }

I recommend using the ErrorProvider control (like you already are), but not using the control's validation at all. 我建议使用ErrorProvider控件(就像您已经使用的一样),但根本不使用控件的验证。 Basically on your button press, you'll check the fields' value and then use the .SetError method on the error provider. 基本上,只要按一下按钮,便会检查字段的值,然后在错误提供程序上使用.SetError方法。

Another method is to use the form's ValidateChildren method. 另一种方法是使用窗体的ValidateChildren方法。 You can track whether validation should occur and only allow validation when you want it Or you can use manipulate the CausesValidation property on all your controls. 您可以跟踪是否应该进行验证,并且仅在需要时才允许验证,或者可以在所有控件上使用CausesValidation属性。 Here is the first option, 这是第一个选择,

    private bool _validate = false;

    private void button1_Click(object sender, EventArgs e)
    {
        _validate = true;
        this.ValidateChildren();
        _validate = false;
    }

    private void textBox1_Validating(object sender, CancelEventArgs e)
    {
           if (_validate==true)
           {
                errorProvider1.SetError(textBox1, "test");
           }
    }

Set the CausesValidation property to false on each control to prevent it from calling the validation methods when focus leaves, explanation here for order of events: 设置在每个控件的CausesValidation属性设置为false,以防止它调用验证方法时,焦点离开,说明事件的顺序:

If the CausesValidation property is set to false, the Validating and Validated events are suppressed. 如果CausesValidation属性设置为false,则将抑制Validating和Validated事件。

Obviously you can re-enable them before calling ValidateChildren if required. 显然,如果需要,您可以在调用ValidateChildren之前重新启用它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM