1

我在 ac#winforms 应用程序中使用 errorprovider。现在我想要一个“双重”验证。一次直接在文本字段上,所以用户看到他犯了一些错误,一次在按钮本身上。因此,当仍有错误时,“保存”按钮将保持灰色或“禁用”状态。

因为我不想在他出错时阻止我的用户,并且我希望他能够在他希望我使用事件“离开”或失去焦点时进行更改。这是因为否则我注意到你不能去另一个领域,直到你改变你的错误。

所以,现在代码:

    private void txtFirstname_Leave(object sender, EventArgs e)
    {
        if (!InputChecks.IsFilledIn(txtFirstname.Text))
        {
            errorProvider1.SetError(txtFirstname, "Firstname needs to be filled in!");
            isValidated = false;

        }
        else
        {
            errorProvider1.SetError(txtFirstname, "");
            isValidated = true;

        }
    }

到目前为止,一切都很好。错误提供程序正常工作,我的用户可以随时编辑。

 public void setSaveButton()
    {
        if (isValidated == true)
        {
            btnSave.Enabled = true;

        }
        else
        {
            btnSave.Enabled = false;
        }   
    }

 bool isValidated;
    private void btnSave_Click(object sender, EventArgs e)
    {

        if (isValidated == true)
        {

            employeePresenter.addEmployee(txtFirstname.Text, txtLastname.Text, txtUsername.Text, txtPassword.Text);
        }



    }

这在我的脑海里仍然是好的。但是,因为我让用户能够随时更改问题,所以这不起作用。我试图将方法“setSaveButton()”放在“isvalidated”下,但这也不起作用。因为失去了焦点。

有人对此有更好的主意吗?我一直在看谷歌,我发现的唯一东西是使用 errorprovider 进行单一验证,或事件验证。但是这些事件不允许用户随时编辑他们的错误。它将它们阻止到一个特定的文本字段中。

4

1 回答 1

3

您无需禁用保存按钮。检查表单的方法就足够了ValidateChildren,如果它返回 false,则意味着存在一些验证错误。要使用这种方法,您应该记住在为控件设置错误时设置控件e.Cancel = true的事件。Validating

即使有错误,也让用户在控件之间移动,在设计器中设置你的AutoValidate属性或使用代码:FormEnableAllowFocusChange

this.AutoValidate = System.Windows.Forms.AutoValidate.EnableAllowFocusChange;

验证代码:

private void txtFirstname_Validating(object sender, CancelEventArgs e)
{
    if (string.IsNullOrEmpty(this.txtFirstname.Text))
    {
        this.errorProvider1.SetError(this.txtFirstname, "Some Error");
        e.Cancel = true;
    }
    else
    {
        this.errorProvider1.SetError(this.txtFirstname, null);
    }
}

private void btnSave_Click(object sender, EventArgs e)
{
    if (this.ValidateChildren())
    {
        //Here the form is in a valid state
        //Do what you need when the form is valid
    }
    else
    {
        //Show error summary
    }
}
于 2016-04-24T19:38:08.587 回答