ImGreg ImGreg - 13 days ago 5
C# Question

Form Validation using ErrorProvider and Validating Events

I'm fairly new to using validation. I have a C# winform project that I want to validate a form before closing. However, I only want this validation to occur when I click a button. So I have an event that fires for that like so:

if (!this.ValidateChildren())
{
MessageBox.Show("Validation failed");
}
else
{
MessageBox.Show("Validation passed with flying colours. :)");
this.Close();
}


I only want to close the form if the validation is successful. Easy enough. However, I don't want to have the validation run when the textboxes lose focus, only when the whole form is being validated.

Each control that I want to be validated, I have registered with the "validating" event. They use "e.Cancel = true;" to cancel the validation. I have been using the ErrorProvider class to support this visually.

So basic question is, what is the best approach to validate a specific set of controls only when I want to and not when focus is lost from the control?

EDIT: presently as a work around, I have a method that toggles the "CausesValidation" property on and off. I default everything to not CauseValidation, enables them all before I use the event for validating the whole form, and disables them all after again.

I really don't see this as an ideal approach. Are there any more 'elegant' solutions out there?

Answer