Datasheet
of all the objects within your application. If you hover your mouse on the combo box on the right, you’ll
see a ToolTip telling you that this is the Method Name combo box. If you expand this combo box, you
will see a list of all defined functions and subroutines for the object selected in the Class Name combo
box. If this particular form had a lot of code behind it, these combo boxes would make navigating to the
desired area very quick — jumping to the selected area in your code. However, since all of the code fits
in the window, there are not a lot of places to get lost.
Try It Out Adding Code to the HelloUser Project
1.
To begin adding the necessary code, click the Design tab to show the form again. Then double-
click the OK button. The code window will open with the following code. This is the shell of the
button’s Click event and is the place where you enter the code that you want to run when you
click the button. This code is known as an event handler and sometimes is also referred to as an
event procedure:
Private Sub btnOK_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnOK.Click
End Sub
As a result of the typographic constraints in publishing, it is not possible to put the Sub declaration on
one line. Visual Basic 2005 allows you to break up lines of code by using the underscore character (_) to
signify a line continuation. The space before the underscore is required. Any whitespace preceding the
code on the following line is ignored.
Sub is an example of a keyword. In programming terms, a keyword is a special word that is used
to tell Visual Basic 2005 to do something special. In this case, it tells Visual Basic 2005 that this is
a subroutine, a procedure that does not return a value. Anything that you type between the lines
Private Sub and End Sub will make up the event procedure for the OK button.
2. Now add the highlighted code into the procedure:
Private Sub btnOK_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnOK.Click
‘Display a message box greeting the user
MessageBox.Show(“Hello,” & txtName.Text & _
“! Welcome to Visual Basic 2005.”, _
“Hello User Message”)
End Sub
Throughout this book, you will be presented with code that you should enter into your program if you
are following along. Usually, we will make it pretty obvious where you put the code, but as we go, we
will explain anything that looks out of the ordinary. The code with the gray background is code that you
should enter.
3. After you have added the preceding code, go back to the Design tab, and double-click the Exit
button. Add the highlighted code to the
btnExit_Click event procedure.
Private Sub btnExit_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnExit.Click
‘End the program and close the form
Me.Close()
End Sub
19
Welcome to Visual Basic 2005
04_574019 ch01.qxd 9/16/05 9:43 PM Page 19