Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
444 views
in Technique[技术] by (71.8m points)

c# - Validation using Validating event and ErrorProvider - Show Error Summary

How to show Messagebox "Data is invalid" when there is errors left in my WinForms. Tried something like but it does not work.

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

Maybe i have to use bool for this solution.

My full code:

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.
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should first correct your validating events this way:

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

Then you should use ValidateChildren method to check if there is a validation error or not, then you can get a list of all errors and show to user this way:

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:
 - " +
            string.Join("
 - ", listOfErrors.ToArray()),
            "Error",  
            MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

A Sample screenshot:

enter image description here

Note:

  • You should not use Clear method of error provider to set valid state to control, you should use SetError, for example this.errorProvider1.SetError(textBox2, "");
  • You should call e.Cancel=true when there is a validation error.
  • In sample codes I assume that all your controls including the error provider placed directly on your form and not in a container control.
  • I also recommend to change validation behavior of form by setting AutoValidate property of form to EnableAllowFocusChange in design time or by code in Load event of form this way:

To change validation behavior of form:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...