Arg - Validating controls on a form

  • Thread starter Thread starter Tom Jones
  • Start date Start date
T

Tom Jones

Hi,

I have a form with a textbox, an errorprovider, and an Ok & Cancel button.

The textbox cannot be empty when the dialog is dismissed. The textbox has
its 'CausesValidation' property set to true. Here is its validation code:

private void tbName_Validating(object sender,
System.ComponentModel.CancelEventArgs e)
{
if (tbName.Text.Length == 0)
{
e.Cancel = true;
tbName.Focus();
epErrorProvider.SetError(tbName, "This field cannot be empty");
}
else
{
epErrorProvider.SetError(tbName, "");
}
}

If the user hits the Ok button without the textbox ever gaining focus the
textbox's validation method never gets called so I check this in the Ok
button's handler:

private void btnOk_Click(object sender, System.EventArgs e)
{
if (epErrorProvider.GetError(tbName) == "")
this.Close();
else
// How do I *stop* the form from being closed here!?
}

My Cancel button has its 'CausesValidation' property set to false and looks
like:

private void btnCancel_Click(object sender, System.EventArgs e)
{
epErrorProvider.SetError(tbName, "");
this.Close(); // We need to cancel so forget about validating the
textbox
}

My problem is that hitting the Ok button before the textbox ever gains focus
causes the form to be dismissed - I *need* the form to stick around until
that textbox has valid data in it (unless the Cancel button was clicked).

How do I get around this issue?

Thanks,
TJ
 
Back
Top