.netvb.netwinforms

TextBox as Trigger


Is there a way to make textbox trigger event by just pressing enter (without button). Basically, I want to input a number and if number passes a threshold it triggers an chain of events. all done in MicrosoftVisualStudio (vb)

Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles     PictureBox1.Click
    Dim t As Double = Val(TextBox1.Text)
    If t >= 60 Then
        PictureBox1.Visible = True
    End If
End Sub

Solution

  • There are two options here:

    1. Handle the Keypress event and check whether the KeyChar property in the arguments is the Enter key. Since this runs for every keystroke, my personal preference is to use a guard clause as early as possible to exit the event method completely unless we have a match:

      If Not e.KeyPress.Equals(ControlChars.Cr) Then Exit Sub
      
    2. Have a hidden button (Visible is False or moved out of the visible area) set as the AcceptButton property for the form, and make that event handler run your code. You may also want to check here whether your desired textbox had focus, similar to how the other option checks where the enter key was pressed vs some other key.