I ran into a problem closing a form where my ErrorProvider wouldn't let me do it. To correct it I made a jerry-rigged creating a variable Boolena to confirm if the form was being closed. I had already tried FormClosing but still the ErrorProvider was validating the focus field. Has anyone had the same problem? How did you solve it? I wanted to do it more elegantly.
Form Initialize
public partial class MyForm: form
{
private bool _isClosing = false;
...
...
}
Generic Validate With Error Provider
private bool ValidatingFields(Control control)
{
bool eventArgs = false;
if (!this._isClosing) //Boolean Variable jerry-rigged
{
if (string.IsNullOrEmpty(control.Text))
{
eventArgs = true;
control.BackColor = Color.Red;
errorProvider.SetError(control, "Campo Obrigatório!");
}
else
{
eventArgs = false;
errorProvider.SetError(control, null);
}
}
return eventArgs;
}
Field Validating
private void textName_Validating(object sender, CancelEventArgs e)
{
e.Cancel = ValidatingFields(textName);
}
Event Close Button Click
private void btnCancel_Click(object sender, EventArgs e)
{
this._isClosing = true;
this.Close();
}
Yeah Nothing wrong in this behavior. Control Validation will trigger any button click event except who's CausesValidation = False. In short you can set this property of the cancel button to "False". This will skip the validation.