How to determine which button was pressed in OnValidating event.

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have a custom control which has it's own OnValidating event handler. I
would like to skip the validations if the Cancel/Exit button is pressed.
Also, if possible, would like to skip the validations if the X was clicked to
close the form. How can I do this?

Thanks,
Vern
 
I have a custom control which has it's own OnValidating event handler. I
would like to skip the validations if the Cancel/Exit button is pressed.

Cancel/Exit buttons on a form should have the CausesValidation property set to "false".
If they are set to "true" for some reason and you want to ignore the validation for your control, then here's a quick solution:

private bool closing = false;
private Form form;

protected override void OnValidating(System.ComponentModel.CancelEventArgs e)
{
base.OnValidating (e);

// A dialog form's cancel button should have the "CausesValidation" property
// set to false, but this will catch that just in case it doesn't :)
if (closing || form != null && form.Modal && form.DialogResult == DialogResult.Cancel)
return;

// Todo: validate
}


protected override void OnParentChanged(EventArgs e)
{
base.OnParentChanged (e);

if (form != null)
form.Closing-=new System.ComponentModel.CancelEventHandler(form_Closing);

if (Parent == null)
return;

form = FindForm();

if (form != null)
form.Closing+=new System.ComponentModel.CancelEventHandler(form_Closing);
}

private void form_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
closing = true;
}
 
Actually, I do have the CausesValidation property set to false for the cancel
button. But it executes the overridden OnValidating routine anyway. Here's
the code that I'd like to do something to get it to ignore the validations.
This code is part of a custom auto-fill combo box control.


protected override void OnValidating(CancelEventArgs e)
{

ShowErrorIcon("");

if (_required && Text == "")
{
OnNotEntered(e);
}
else
{
if (_limitToList && Text != "")
{
int pos = FindStringExact(Text);
if (pos == -1)
OnNotInList(e);
else
this.SelectedIndex = pos;
}
}
base.OnValidating(e);
}
 
Back
Top