2

I have a small problem with validating userinput in textboxes.

There is a usercontrol with various textboxes in which users can enter data to add a new record to the database. When either of these textboxes does not have a correct value (null or specific) I want the inserting to be cancelled and have the 'errormaking' textbox receive focus.

This has to be checked via a button. Can I call the Validating event of the button, or is there a different (better) way to acchieve this?

Also, there is a Cancel button to cancel the entire inserting. When trying to use the errorprovider, the Cancel button became unavailable aswell, because the field were empty so it could not send.

Some code for reference:

private void CheckInput(CancelEventArgs e, TextBox tb)
    {
        ErrorProvider error = new ErrorProvider();
        if (string.IsNullOrEmpty(tb.Text))
        {
            error.SetError(tb, "*");
            e.Cancel = true;
        }

        if (!string.IsNullOrEmpty(tb.Text)) 
        {
            error.SetError(tb, string.Empty);
            error.Clear();
            error.Dispose();
        }
    }

1 Answer 1

6

Create single instance of ErrorProvider and place it on your form. Do not create error provider during validation of each separate control. Then subscribe to textbox Validating event (you can use same handler for all textboxes):

private void textBox_Validating(object sender, CancelEventArgs e)
{
    TextBox tb = (TextBox)sender;

    if (String.IsNullOrEmpty(tb.Text))
    {
        errorProvider.SetError(tb, "*");
        e.Cancel = true; 
        return;          
    }

    errorProvider.SetError(tb, String.Empty);
}

In order to avoid validation when you are clicking Cancel button, set it's CauseValidation property to false.

UPDATE: Thus you are validating controls in user control, you should disable that validation when you are clicking Cancel buttong:

private void CancelButton_Click(object sender, EventArgs e)
{
    userControl.AutoValidate = AutoValidate.Disable;
    Close();
}
Sign up to request clarification or add additional context in comments.

2 Comments

This still does not fix my problem of enabling users to click the Cancel button, if textboxes are left empty. How do I fix that?
I actually tried that. The form still does not close (On_click of cancelbutton the form closes). Does this have anything to do with the fact that the input is being done inside a Usercontrol, but the buttons are outside of it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.