我在winforms c#项目中对texbox组件进行验证时遇到问题。

我在“创建产品”表单中有几个文本框,用于验证数字,空字符串等。如果我从一个带有验证的文本框转到另一个文本框,则会触发验证事件,并且我无法更改焦点,即即时消息停留在文本框上,直到我键入内容为止。我一直在寻找的行为应该在我点击“创建按钮”时触发文本框上的验证事件,而不是当我将焦点从一个文本框更改为另一个文本框时触发。

有什么提示或良好做法,如何解决呢?非常感激..

当前代码:

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

最佳答案

我建议使用ErrorProvider控件(就像您已经使用的一样),但根本不使用控件的验证。基本上,只要按一下按钮,便会检查字段的值,然后在错误提供程序上使用.SetError方法。

另一种方法是使用表单的ValidateChildren方法。您可以跟踪是否应该进行验证,并且仅在需要时才允许验证,或者可以在所有控件上使用CausesValidation属性。这是第一个选择,

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

关于c# - 更改文本框焦点时,停止触发验证事件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19317012/

10-17 00:53