Camilo Martin
Camilo Martin

Reputation: 37908

VB.NET: Dialog exits when enter pressed?

My problem seems to be quite simple, but it's not working the intuitive way.

I'm designing a Windows Forms Application, and there is a dialog that should NOT exit when the enter key is pressed, instead it has to validate data first, in case enter was pressed after changing the text of a ComboBox.

I've tried by telling it what to do on KeyPress event of the ComboBox if e is the Enter key:

Private Sub ComboBoxSizeChoose_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles ComboBoxSizeChoose.KeyPress
    If e.KeyChar = Convert.ToChar(Keys.Enter) Then
        Try
            TamanhoDaNovaFonte = Single.Parse(ComboBoxSizeChoose.Text)
        Catch ex As Exception
            Dim Dialogo2 As New Dialog2
            Dialog2.ShowDialog()
            ComboBoxSizeChoose.Text = TamanhoDaNovaFonte
        End Try
    End If
End Sub

But no success so far. When the Enter key is pressed, even with the ComboBox on focus, the whole dialog is closed, returning to the previous form. The validation is NOT done at all, and it has to be done before exiting. In fact, I don't even want to exit on the form's enter KeyPress, the only purpose of the enter key on the whole dialog is to validate the ComboBox (but only when in focus, for the sake of an intuitive UI).

I've also tried appending the validation to the KeyPress event of the whole dialog's form, if the key is Enter. NO SUCCESS! It's like my code wasn't there at all.

What should I do?

(Visual Studio 2008, VB.NET)

Upvotes: 2

Views: 4832

Answers (2)

Marc
Marc

Reputation: 9354

Although not your answer, I would recommend against using exceptions to control logic flow. That said, try Single.TryParse instead to make your flow less...well, exceptional.

To change the behavior you are seeing, change the dialog's AcceptButton from your Ok button to none. Changing that button's DialogResult to None doesn't keep the click event from firing, only from closing the dialog. Although the behavior may sound like something you desire, the result does not.

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564731

Make sure you don't have a Button on the dialog that is set to something other than DialogResult.None.

For example, if you have a button set to DialogResult.OK, it will act as the "default" button and close your form.

Upvotes: 4

Related Questions