Windows Form Cancel Button Not Working

Paul Williams picture Paul Williams · Feb 1, 2012 · Viewed 12.3k times · Source

I have a Visual Studio, Visual Basic form that includes an OK button and a Cancel button.

What I want to do is have the OK button save the options that the user chooses and of course the Cancel button discarding them and returning them to their previous values.

But what I'm noticing is that as I'm debugging the form, the values are being saved regardless of whichever button I'm choosing. On the form's properties, I have declared that indeed the CancelBtn is the CancelBtn and that the OK button is the OK button, but the values are still being saved regardless.

Is there a better way to do what I would like this form to do?

EDIT:

Here's the code so far for the two buttons, both are being set to close the window. AcceptOption should save the values and CancelOption should just close the form. I'm sorry if this isn't done well but the FAQ's that I found only mention changing the properties of each button and nothing about the code.:

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles AcceptOptionBtn.Click
    ' Save the Options
    Me.Close()
    ' Close the form
End Sub

Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles CancelOptionBtn.Click
    ' Close the form
    Me.Close()
End Sub

Answer

Jodrell picture Jodrell · Feb 1, 2012

Don't change "the values" until the user clicks the Save button.

The form should be preloaded with a copy of the values you would like to update.

The Cancel button should just close the form.

The Save button should cause "the values", not the forms copy, to be updated.

EDIT:-

In regard to this question, there is nothing wrong with the code you have posted. Are the right handlers being called for the right button clicks? Are the form's AcceptButton and CancelButton properties set to the right buttons?

What data are your editing controls bound to, if at all?