Coding
You are now going to write your first bit of Visual Basic code!
In the cmdOK_Click() procedure, enter the following:
MsgBox "Hello " & txtName.Text & "!"
What this code does is displays what is known as a Message
Box, which says 'Hello x!', where x is the text in the Text box. Message
Boxes are used throughout Windows for displaying messages and asking questions
in a standard window. Convieniently, it means that you don't have to create
a form yourself to display a simple message.
To see this in action, save your work, and click the Run button
on the toolbar again (you can also press the F5 key). Enter your name into the
text box, and click OK. You should see something like this:
Click OK, and click the close button on the form to return to
design time. Let's take another close look at the code. First of all, the MsgBox
text is actually a Function or Procedure, that VB provides as standard.
This MsgBox function displays a Message Box dialog. After that, there is "Hello
" & txtName.Text & "!". This is actually the text
displayed in the Message Box, placed in quotes. However, we can't simply write
"Hello James!"
as we don't know what the user will enter into the textbox, and
therefore what name to display. If you knew exactly what the message would be,
you could do that. In this instance, we need to get the text from the Text box
on our form. This is done using txtName.Text. txtName
refers to the text box on the form (because we called it txtName). The period
(.) means that we are 'accessing' a property from this control.
Text refers to the property we want to read.
When we do this, Visual Basic returns the Text property; what
is entered in the Text box. As the txtName.Text is actually VB
code, and not simply the text we want displayed, it needs to be outside of the
quotes. If we simply wrote
MsgBox "Hello txtName.Text!"
you would get
which is certainly not what we wanted. Instead, we close the quote
after Hello (and a space, so that there is a gap between Hello and the name).
Next we use the ampersand (&) symbol to say that we want the text Hello,
and then something else. We then place the code txtName.Text to retreive the
text in the Text box, and then another ampersand and "!" to add an
exclamation mark to the text, ending up with
"Hello " & txtName.Text & "!"