Dialogs in Visual Basic

At this point, we have used the mouse to enter all of the information the program needed. (Scroll bars, option buttons, check boxes, command buttons, and menu choices.) There are some kinds of information that the user must type. In this chapter, we will look at ways for the user to enter text.

Text Boxes: textbox

A label label is used to display information, but a textbox allows the user to enter text.

Greetings
The "Greetings" program uses a text box for the user to type his name. As the user types, the name appears (letter by letter) in the caption.

  1. Start a new Windows application and name it Greetings.
  2. Build the form as shown with a label names lblPrompt and a textbox named txtName.
  3. Write the code as shown below:
'Programmer: Janet Joy
'Illustrate using a text box
Public Class Form1
    Private Sub TxtName_TextChanged(sender As Object, e As EventArgs) Handles TxtName.TextChanged
        Me.Text = "Hello " & Me.TxtName.Text
    End Sub
End Class

The next version of the Greeting Program waits until the user presses ENTER then displays the name in the caption. When a change is made in the text box, the caption is changed to just "Hello". Without this line, the caption would still display the name of the first person while the second person was typing his name.

'Programmer: Janet Joy
'Illustrate using text box key press event
Public Class Form1
    Private Sub TxtName_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TxtName.KeyPress
        If e.KeyChar.Equals(Chr(13)) Then 'Enter is pressed
            Me.Text = "Hello " & TxtName.Text
        Else
            Me.Text = "Hello"
        End If
    End Sub
End Class

NEXT: Input Boxes