验证一个方法C#

时间:2013-04-17 13:29:08

标签: c# validation

如果我有一个验证方法Method1,它返回e.Cancel true或false,如下所示:

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 我怎么能做到这一点?

3 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:1)

这样的东西?

var cnclEvent = new CancelEventArgs();

textBox1_Validating_1(null, cnclEvent);
if (cnclEvent.Cancel) return;

答案 2 :(得分:0)

    public bool IsValidated()
    {
    return !String.IsNullOrEmpty(textBox1.Text);
    }
private void button4_Click(object sender, EventArgs e)
{
        bool passed = IsValidated();
}