Whizzil
Whizzil

Reputation: 1364

Validation - (Form) Cancel button doesnt work

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

Answers (3)

Manish Mishra
Manish Mishra

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.

  1. 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();
    }
    
  2. 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

Tony Hopkinson
Tony Hopkinson

Reputation: 20320

Add a private boolean member, set it true in CancelButtonClicked and then use it in the validation(s)

Upvotes: 0

Shaiju Poozhikkunnu
Shaiju Poozhikkunnu

Reputation: 96

do you miss the line this.Close()

Upvotes: -1

Related Questions