0

如果我有一个Method1返回 e.Cancel 真或假的验证方法,它看起来像这样:

private void textBox1_Validating_1(object sender, CancelEventArgs e)
{
    ErrorProvider errorProvider = new ErrorProvider();

    bool isEmpty = String.IsNullOrEmpty(textBox1.Text);
    if (isEmpty)
    {
        e.Cancel = true;
        errorProvider.SetError(textBox1, "txt");
    }
    else
    {
        e.Cancel = false;
        errorProvider.SetError(textBox1, "");
    }
}

我想在我的另一种方法中获得验证结果:

private void button4_Click(object sender, EventArgs e)
{
    //bool passed = this.Validate(textBox1_Validating_1);
    if (passed == false) return;

我想要这样的东西:

bool passed = this.Validate(textBox1_Validating_1);

仅验证这一种方法。我该怎么做?

我可以这样做:

            bool passed = this.ValidateChildren();
        if (passed == false) return;

但是如果我这样做,那么我会验证我所有的方法,但我只想验证这个Method1 我怎么能做到这一点?

4

3 回答 3

2

我建议创建一个单独的验证方法并在提交时调用它。尝试这个 :

 private void SubmitButton_Click(object sender, EventArgs e)
    {
        if (ValidateControls()==0)
        {
           //Form is validated
        }
    }

int ValidateControls()
{
    int flag = 0;
    errorProvider1.Clear();
    if (txtAge.Text.Trim() == String.Empty)
    {
        errorProvider1.SetError(txtAge, "Age is required");
        flag = 1;
    }
    ............................................
    ............................................
   // validate all controls
    ............................................
    ............................................

    if (txtSalary.Text.Trim() == String.Empty)
    {
        errorProvider1.SetError(txtSalary, "Salary is required");
        flag = 1;
    }

    return flag;
}
于 2013-04-17T13:36:31.587 回答
1
    public bool IsValidated()
    {
    return !String.IsNullOrEmpty(textBox1.Text);
    }
private void button4_Click(object sender, EventArgs e)
{
        bool passed = IsValidated();
}
于 2013-04-17T13:33:50.723 回答
1

像这样的东西?

var cnclEvent = new CancelEventArgs();

textBox1_Validating_1(null, cnclEvent);
if (cnclEvent.Cancel) return;
于 2013-04-17T13:36:33.047 回答