Compile error

Cecilia

Member
Joined
Aug 14, 2007
Messages
24
Programming Experience
Beginner
Hi, I am a very beginner to VB, my new job involves quite some VB programming. I have a compile error here that I don't know how to handle, appreciate it if anyone could help.

...
Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
...
...
End Sub

...

Private Sub z_KeyPress(ByVal KeyAscii As Integer)
'where KeyAscii=13 denotes the Enter key.
If (KeyAscii = 13) Then
OK_Click()
End If

End Sub

All I want to do is that when you press ENTER key, it does what you do by clicking the OK button. But what are the 'sender' and 'e' parameters I needt to call?

Thanks!
 
Is Z the name of your form? Look at this example. Form1 is the name of my form, and Button1 is your "OK" button.
VB.NET:
Public Class Form1
    Private Sub Form1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
        If e.KeyCode = Keys.Enter Then
            Button1_Click(sender, e)
        End If
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        MessageBox.Show("Button1 was triggered by the Enter key")
    End Sub
End Class

Since the form's KeyDown event already has it's own "sender" and "e" arguments, I just used those to raise the event.
 
Thanks for your answer. z is not the form name, but a TextBox's name. There are 2 other TextBox, x and y, which hold 2 integer numbers, the user needs to feed z with the sum of x and y, then press Enter in z to trigger OK button which will show it is correct or not in an label. I tried

Private Sub Form1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
If e.KeyCode = Keys.Enter Then
Button1_Click(sender, e)
End If
End Sub

There is no compile error any more, but when user enter the answer in z and press Enter, it does nothing but giving out a beep.
 
Each control has its own events, you want KeyDown for textbox, not form.
PerformClick is the way to go to trigger button click in code.
 
It finally works! I am sorry if I confused you, the case is I copied some VB 6 old code into a new VB Windows Form project, and I know very little about either VB 6 or VB. NET, now I got it through both of your answers. Thanks!
 
I knew I had seen the PerformClick() function somewhere before, but I hadn't used it before and couldn't come up with what it was last night. :)
 
Back
Top