2
votes

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

1 Answers

5
votes

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