Reputation: 1364
I am having problems with leaving my Form on CancelButton_Clicked
event, because of my Validating
events.
I have one textbox which has its own validating methods, and returns e.Cancel = true
if input String is null or empty, else e.Cancel = false
.
Now, i have this CancelButton
which is just a regular button, and for which I would like to close the current form, somewhat like this:
CancelButton_Clicked(Object sender, EventArgs e)
{
this.Close();
}
But if I do it like this, and if the textbox is left empty it doesnt pass validation, and I cant close the form. Validation icons just keep blinking.
I tried setting CausesValidation
to false
, I tried also this:
private void btnCancel_Click(object sender, EventArgs e)
{
// Stop the validation of any controls so the form can close.
AutoValidate = AutoValidate.Disable;
Close();
}
But none of this helped. Hope you could. Cheers
Upvotes: 2
Views: 2449
Reputation: 12375
am assuming, you have set btnCancel.CausesValidation=false;
either through code or designer.
setting CausesValidation=false
of button
, will allow you to call the Click
event
of the button
now there are multiple things you can do.
simply unregister your textbox
validating
events inside btn_Cancel
i.e.
private void btnCancel_Click(object sender, EventArgs e)
{
textBox1.Validating -= new CancelEventHandler(textBox1_Validating);
this.Close();
}
simply use a boolean flag. set it to true inside your btnCancel event and use it inside validating event
bool IsCancelBtnClicked=false;
private void btnCancel_Click(object sender, EventArgs e)
{
IsCancelBtnClicked=true;
this.Close();
}
private void textBox1_Validating(object sender, CancelEventArgs e)
{
e.Cancel=!IsCancelBtnClicked;
}
Upvotes: 3
Reputation: 20320
Add a private boolean member, set it true in CancelButtonClicked and then use it in the validation(s)
Upvotes: 0