Whizzil
Whizzil

Reputation: 1364

Validate one method C#

If I have one validating method Method1 which returns e.Cancel true or false, and which looks like this:

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

And I want to get the result of validation, in my other method, here:

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

I would want something like this:

bool passed = this.Validate(textBox1_Validating_1);

Only to validate this one method. How do I do it?

I am able to do it like this:

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

But if I do that, then I validate all my methods, but I one want to validate just this one Method1 How can I accomplish this?

Upvotes: 0

Views: 5479

Answers (3)

Serge
Serge

Reputation: 6712

Something like this?

var cnclEvent = new CancelEventArgs();

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

Upvotes: 1

Mohammad Arshad Alam
Mohammad Arshad Alam

Reputation: 9862

I will suggest to create a separate method for validation and call it on submit. Try this :

 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;
}

Upvotes: 2

Dr Schizo
Dr Schizo

Reputation: 4386

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

Upvotes: 1

Related Questions