jbbarnes77
jbbarnes77

Reputation: 239

Overriding OK and Cancel buttons in a dialog

I added a simple LoginForm dialog to my VB.Net program so users can enter name and password. The automatically generated code for the OK and Cancel buttons just calls Close(). I want to prompt the user with a question before I allow the dialog to close. Here is a brief example of what I did:

Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
    If PasswordTextBox.Text.Length < 8 Then
        MessageBox.Show("Passwords must be at least 8 characters long.")
    Else
        Me.Close()
    End If
End Sub

Private Sub Cancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cancel.Click
    Dim Result As DialogResult = MessageBox.Show("Are you sure you want to quit the program " +
        "without logging in?", "Login incomplete", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
    If Result = DialogResult.Yes Then
        Me.Close()
    End If
End Sub

So I am trying to bypass the default Close() behavior, but the dialog still closes and returns the OK or Close value to the caller in every circumstance. How can override this behavior?

Upvotes: 0

Views: 1148

Answers (1)

Steve
Steve

Reputation: 216243

A button has a DialogResult property and, when this property is set to something different than None, clicking that button automatically closes the dialog. You can use this behavior to write simpler code in your button event handlers

Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
    If PasswordTextBox.Text.Length < 8 Then
        MessageBox.Show("Passwords must be at least 8 characters long.")
        ' Not good, stop the form's closure.
        Me.DialogResult = DialogResult.None
    End If
End Sub

In this example I block the default behavior of the button only if there is something that is not right. Setting the form's DialogResult property to DialogResult.None blocks the default closure when you press a button with a DialogResult property set to something different than None.

The same approach could be used for your cancel button

Upvotes: 1

Related Questions