If a user presses enter in a textbox, i want to activate a button that's next to it. What's the easiest way to do this?
Printable View
If a user presses enter in a textbox, i want to activate a button that's next to it. What's the easiest way to do this?
Handle the KeyDown event of the TextBox and call the PerformClick event of the Button.
Or assign that button to your form's AcceptButton property.
Check to see if "Enter" was pressed, then do whatever you want.
vb Code:
Private Sub Text1_KeyPress(KeyAscii As Integer) If KeyAscii = vbKeyReturn Then MsgBox "Enter" Button1.SetFocus Else MsgBox "Not Enter" End If End Sub
That's VB6 code and it will not work on VB.Net application.Quote:
Originally Posted by wes4dbt
Thanks all. Well this is my solution
But I was hoping that such a common function would be supported as something that's precoded as an option, like the way you can set a combobox to suggest completions. AcceptButton is a good idea, but I have many textboxes and buttons on the same form. If I suggest Microsoft to add this functionality to the next VS would they do it? :lol:Code:Private Sub TextBoxUsersName_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBoxUsersName.KeyPress
If e.KeyChar = Microsoft.VisualBasic.ChrW(Windows.Forms.Keys.Return) Then
ButtonUsersName_Click(TextBoxUsersName, e)
End If
End Sub
Thanks all.
You should replace this line
With thisCode:ButtonUsersName_Click(TextBoxUsersName, e)
Code:ButtonUsersName.PerformClick()
Any reason why PerformClick is better?
Sorry I thought I was in the VB6 forum.
I guess I'll have to get my eyes checked.
Haha no worries. I recognized the VB6-ishness of it :bigyello:.Quote:
Originally Posted by wes4dbt
It's the proper way to trigger a button click in code. While calling the method directly and suppy it with parameters (as you're doing) does work, it's generally considered to be bad practice.Quote:
Originally Posted by Daarklord
And that concludes my quick question about pressing enter. :wave: