使用 Validating 事件和 ErrorProvider 进行验证 - 显示错误摘要

2024-01-21

当我的 WinForms 中存在错误时,如何显示消息框“数据无效”。 尝试过类似的东西,但它不起作用。

if (errorprovider1 == !null)
{
 MessageBox.Show("Data is invalid");
}

也许我必须使用 bool 来解决这个问题。

我的完整代码:

private void Form1_Load(object sender, EventArgs e)
{
    this.Text = "Formas elementu validācija";
}

    private void textBox1_Validating(object sender, CancelEventArgs e)
    {
        Regex regex1 = new Regex(@"^[a-zA-Z]+$");
        if (!regex1.IsMatch(textBox1.Text))
        {
            errorProvider1.SetError(textBox1, "Nosaukums nedrīskt saturēt ciparus!");
        }
        else
        {
            errorProvider1.Clear();
        }
    }

    private void textBox2_Validating(object sender, CancelEventArgs e)
    {
        Regex regex1 = new Regex(@"^[0-9]+$");
        if (!regex1.IsMatch(textBox2.Text))
        {
            errorProvider2.SetError(textBox2, "Reģ.nur drīkst saturēt TIKAI ciparus!");
        }
        else
        {
            errorProvider2.Clear();
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        // if errorProvider1 is empty (no errors) , show messagebox with text: All data correct.
        // else Data is incorrect.
    }

您应该首先以这种方式更正您的验证事件:

private void textBox1_Validating(object sender, CancelEventArgs e)
{
    Regex regex1 = new Regex(@"^[a-zA-Z]+$");
    if (!regex1.IsMatch(textBox1.Text))
    {
        //To set validation error
        errorProvider1.SetError(textBox1, "Nosaukums nedrīskt saturēt ciparus!");
        //To say the state of control in invalid
        e.Cancel = true;
    }
    else
    {
        //To clear the validation error
        this.errorProvider1.SetError(this.textBox1, "");
    }
}

那么你应该使用ValidateChildren https://msdn.microsoft.com/en-us/library/system.windows.forms.form.validatechildren(v=vs.110).aspx方法来检查是否存在验证错误,然后您可以获取所有错误的列表并以这种方式显示给用户:

private void button1_Click(object sender, EventArgs e)
{
    if (this.ValidateChildren())
    {
        //Here the form is in valid state
        //Do what you need when the form is valid
    }
    else
    {
        var listOfErrors = this.errorProvider1.ContainerControl.Controls.Cast<Control>()
                               .Select(c => this.errorProvider1.GetError(c))
                               .Where(s => !string.IsNullOrEmpty(s))
                               .ToList();
        MessageBox.Show("Please correct validation errors:\n - " +
            string.Join("\n - ", listOfErrors.ToArray()),
            "Error",  
            MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

示例截图:

Note:

  • 你不应该使用Clear https://msdn.microsoft.com/en-us/library/system.windows.forms.errorprovider.clear.aspx错误提供者的方法来设置有效状态来控制,您应该使用SetError https://msdn.microsoft.com/en-us/library/system.windows.forms.errorprovider.seterror(v=vs.110).aspx, 例如this.errorProvider1.SetError(textBox2, "");
  • 你应该打电话e.Cancel=true当出现验证错误时。
  • 在示例代码中,我假设所有控件(包括错误提供程序)都直接放置在表单上,​​而不是放置在容器控件中。
  • 我还建议通过设置来更改表单的验证行为AutoValidate形式的属性为EnableAllowFocusChange在设计时或通过代码Load事件的形式如下:

要更改表单的验证行为:

this.AutoValidate = System.Windows.Forms.AutoValidate.EnableAllowFocusChange;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Validating 事件和 ErrorProvider 进行验证 - 显示错误摘要 的相关文章

随机推荐