VB .NET Chapter 2 Write your first .NET code


How to Create Variables in VB .NET

Why are we discussing variables? And what is a variable?
With Visual Basic, and most programming languages, what you are doing is storing things in the computer's memory, and manipulating this store. If you want to add two numbers together, you put the numbers into storage areas and "tell" Visual Basic to add them up. But you can't do this without variables.
So a variable is a storage area of the computer's memory. Think of it like this: a variable is an empty cardboard box. Now, imagine you have a very large room, and in this room you have a whole lot of empty cardboard boxes. Each empty cardboard box is a single variable. To add two numbers together, write the first number on a piece of paper and put the piece of paper into an empty box. Write the second number on a piece of paper and put this second piece of paper in a different cardboard box.
Now, out of all your thousands of empty cardboard boxes two of them contain pieces of paper with numbers on them. To help you remember which of the thousands of boxes hold your numbers, put a sticky label on each of the two boxes. Write "number1" on the first sticky label, and "number2" on the second label.
What have we just done? Well, we've created a large memory area (the room and the cardboard boxes), and we've set up two of the boxes to hold our numbers (two variables). We've also given each of these variables a name (the sticky labels) so that we can remember where they are.
Now examine this:
Dim number1 As Integer
Dim number2 As Integer
number1 = 3
number2 = 5
That's code from Visual Basic Net. It's VB's way of setting up (or declaring) variables.
Here's a breakdown of the variable Declaration:
Dim
Short for Dimension. It's a type of variable. You declare (or "tell" Visual Basic) that you are setting up a variable with this word. We'll meet other types of variables later, but for now just remember to start your variable declarations with Dim.
number1
This is the cardboard box and the sticky label all in one. This is a variable. In other words, our storage area. After the Dim word, Visual Basic is looking for the name of your variable. You can call your variable almost anything you like, but there are a few reserved words that VB won't allow. It's good practice to give your variables a name appropriate to what is going in the variable.
As Integer
We're telling Visual Basic that the variable is going to be a number (integer). Well meet alternatives to Integer later.
Number1 = 3
The equals sign is not actually an equals sign. The = sign means assign a value of. In other words, here is where you put something in your variable. We're telling Visual Basic to assign a value of 3 to the variable called number1. Think back to the piece of paper going into the cardboard box. Well, this is the programming equivalent of writing a value on a piece of paper
Now that you have a basic idea of what variables are, let's write a little piece of code to test them out. First, though, let's have our first look at the coding window.
To make life easier, we're going to put a button on our form. When our button is clicked, a little message box will pop up. Fortunately, there's no coding to write for a button, and very little at all for a message box.

Adding a Button to a Form

Instead of double clicking the Button tool in the toolbox to add the control to the form, we'll explore another way to do it.
With your Form displayed in the Visual Basic Design environment, do the following:
  • Click on the Button tool in the toolbox with the left hand mouse button, but click only once
  • Move your mouse to a blank area of your form - the mouse pointer will turn into a cross
  • Press and hold down the left mouse button
  • Drag across the form with the button held down
  • Let go of the mouse button when you're happy with the size
  • A Button is drawn
You can use the above method to draw most of the controls onto the form - labels, Buttons, textboxes, etc.
The Button control, just like all the other controls we've seen so far, has a list of properties. One of these properties is the Text property. At the moment, your button will say "Button 1". You can change that to anything you like.
  • Click on the Button to highlight it
  • Click on Text in the Property Box
  • Click in the box next to the word "Text"
  • Delete the word "Button 1"
  • Type "Add two numbers"
  • Click back on the Form
Now add a Textbox to your form using one of the methods outlined (either double-click, or draw).
Your Form should now look something like this:
The Font property of the Button has also been changed, here, in exactly the same way as we changed the Font property of the Label and Textbox previously. The Text for the Textbox control has had its default Text (Textbox 1) deleted.
To get our first look at the code window, double click your Button control. The code window will appear, and will look like this in version 2010:
VB NET code stub for a Button
And this in version 2012/13:
Button code, VB NET 2012
In the 2010 version, notice that we've used the underscore character ( _ ) to spread the code over more than one line. You can do this in your own code, if it becomes too long. But you don't have to.
In the 2012/13 version, notice that the word ByVal is missing between the round brackets. Don't worry about what this means, but we'll cover it much later. (It's still ByVal, in case you're curious, but it's missing because ByVal the default type.)

The part to concentrate on for the moment is where your cursor is flashing on and off. Because you double-clicked the Button control, the cursor will be flashing between the lines Private Sub … and End Sub.
Here's the part we're concentrating on:

Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles Button1.Click
End Sub
The part of the code we're interested in is highlighted in red in the code above. Notice, too, that the underscore character ( _ ) has been used to spread the code over more than one line. You can do this in your own code, too, if it becomes to long:
Private
Private means that no other part of the programme can see this code except for our button
Sub
Short for Subroutine. The "Sub" word tells VB that some code follows, and that it needs to be executed
Button1
This is the name of our button. You might think that we've just erased the word "Button1" when we changed the Text property, so why does VB insist that it's still called Button1? We'll, the Name property of the control is the important one. If you change the Name property, VB will change this button name for you
_Click ( )
This is something called an Event. In other words, when the button is clicked, the Click Event will fire, and the code we're going to write will be executed
End Sub
The subroutine ends right here. This signifies the end of our code

Don't worry if you don't understand all of that. It will become clearer later.

Writing your first .NET code

The Text Property of a Control

We'll add some code right now.
Click your mouse on the blank line after Private Sub Button1_Click, etc, but before End Sub. Type the following code:
Dim number1 As Integer
Dim number2 As Integer
Dim answer As Integer
number1 = 3
number2 = 5
answer = number1 + number2
MsgBox answer
After typing all that, your code window should now look like this in version 2010 of Visual Studio Express. The only difference in version 2012 is the missing keyword ByVal:
The VB .NET code window
Before we explore what's happening here, save your work and then click Debug > Start from the Visual Basic Menu, or press F5 on your keyboard. This will launch your programme. Click the Button once, and you should get the following:
Stop your programming, and return to the Design Environment. If you can't see your code, you can click the Tabs at the top of the Window, as in the image below:
The Tabs windows in NET
Click the "Form1.vb [Design]" tab to see your Form.
OK, what happened there? Well, what happened is we've just wrote a programme to add two numbers together, and we displayed the result by using a Message Box - you very first real programme! But let's break that code down a little more.
  • First, we started with the Dim word, indicating to Visual Basic that we wanted to set up a variable
  • Then we gave the variable a name (number1)
  • Next, we "told" VB that what is going inside the variable is a number (As Integer)
  • Two more variable were set up in the same way, number2 and answer
After setting up the three variables, here's what we did:
  • Told Visual Basic that what is going into the first variable was the number 3, and what is going into the second variable was the number 5. To put something into a variable, you use the equals ( = ) sign. But it's not really an equals sign - it's an assignment operator. You are assigning the value of 3 to the variable called number1
number1 = 3
number2 = 5
The next part is a little bit more complicated, but not too complicated. What we wanted to do was to add two numbers together. So we said
number1 + number2
Visual Basic already knows how to add up: all we need to do is "tell" it to add up. We do the "telling" in the traditional, mathematical way - with the plus sign (+). What Visual Basic will do is to look at what we've stored inside number1, and look at what's inside number2. It's sees the 3, sees the five, and also sees the plus sign. Then Visual basic adds them up for you.
Except we also did something else. We said to Visual Basic "When you've finished adding up the two variables number1 and number2, store the result in that other variable we set up, which is called answer."So, the whole line
answer = number1 + number2
means: "Add the variable called number1 to the variable called number2. Then store the result in the variable called answer."
Think of it as working from the right-hand side of the equals sign first. Then when you have the answer, assign it the variable on the left of the equals sign.
The final part of the programme used Visual Basic's in-built Message Box. We'll learn a more about the Message Box later. For now, think of it as a handy way to display results.
Message boxes are quite handy when you want to display the result of some code. But we have a textbox on the form, and we might as well use that.
So delete the line: MsgBox answer. Type the word Textbox1, then type a full stop. You should see a drop-down box appear. This is a list of the Properties and Methods that the Textbox can use.
IntelliSense in VB .NET
Scroll down until you see the word "Text". Double click the Text property and the drop-down box will disappear. (This drop-down box is known as IntelliSense, and is very handy. It means you can just select a property or method from the list without having to type anything.)


The Text property you have chosen is the same Text property that you set from the Properties Window earlier. Here, we're setting the property with our code; before, we set it at design time. But the result is the same - the Text property of the textbox will be set to a value of our choosing.
To set a value, type an equals sign, then type a value for the Text property. We want the contents of the variable called answer to appear in the textbox. So the rest of the code is just this:
Textbox1.Text = answer
Your code window should then look like this:
Transfer the answer to the text box
Run your code again, and press the Button on the form. You should see the number 8 appear in the textbox.
OK, time for your first exercises. They're not too painful, and hopefully they'll giver you a better idea of what variables are. And besides, programming is about doing, not talking. So off we go!

Exercise

Delete the values 3 and 5 and replace them with numbers of your own

Exercise

Delete the plus sign in between number1 and number2, and replace them with each of the following in turn

- (the minus sign)
* (the multiplication sign in VB is the asterisk sign)
/ (the divide sign in VB is the forward slash)

Exercise A

Set up another Integer variable. Give it the name number3. Assign a value of 10 to this new variable. Multiply the value of your new variable by the variable called answer. Display the result in your textbox.

(Another way to assign values to variables is when you first set them up. You can do this:
Dim number3 As Integer = 10
This is exactly the same as saying:
Dim number3 As Integer
number3 = 10
It's up you which method you use. But the objective is the same - to assign a value to a variable.)

String Variables

An Introduction to Programming Strings


So we've learnt something about variables, what they are and how to set one up. We learnt about the word "integer", and that integer variables held numbers. But what if we don't want numbers? After all, our first Form asked users to type in their First Name and Last Name. Names are not numbers, so what do we do then? Well that's where Strings come in.
What is a String? Actually a string is nothing more than text. And if we want Visual Basic to store text we need to use the word "String". To set up a variable to hold text we need to use As String and not As Integer. If the information we want to store in our variables is a First Name and a Last Name, we can set up two variables like this.
Dim FirstName As String
Dim LastName As String
Again we've started with the Dim word. Then we've called the first variable FirstName. Finally, we've ended the line by telling Visual Basic that we want to store text in the variable - As String.
So we've set up the variables. But there is nothing stored in them yet. We store something in a variable with the equals sign ( = ). Let's store a first name and a last name in them
FirstName = "Bill"
LastName = "Gates"
Here, we said to Visual Basic "Store the word 'Bill' into the variable FirstName and store the word 'Gates' into the variable called LastName. But pay attention to the quotation marks surrounding the two words. We didn't say Bill, we said "Bill". Visual Basic needs the two double quotation marks before it can identify your text, your String.
So remember: if you're storing text in a variable, don't forget the quotation marks!
To test all this out, add a new Button to your Form. Set the Text property of the Button to "String Test". Your Form would then look like this (it will look rather grey and dull in newer version of Visual Studio Express):
VB Net Form to test string variables
Double click your new button, and add the following code:
Dim FirstName As String
Dim LastName As String
Dim FullName As String
FirstName = "Bill"
LastName = "Gates"
FullName = FirstName & LastName
Textbox1.Text = FullName

Your code window should now look like this (some of the first line has been cropped in the image below):
VB .NET code window
There's a line there that needs explaining
FullName = FirstName & LastName
In the two lines of code above that one, we stored the string "Bill" and the string "Gates" into two variables. What we're doing now is joining those two variables together. We do this with the ampersand symbol ( & ). The ampersand is used to join strings together. It's called Concatenation.
Once Visual Basic has joined the two strings together (or concatenated them), we're saying "store the result in the variable called FullName". After that, we tell VB to display the result in our Textbox.
So, once you've typed the code, start your programme and test it out.
Once the programme is running, Click the Button and see what happens. You should have a Form that looks something like this one:
The name appears in the text box
The textbox displays the text stored in our variables, "Bill" and "Gates". We joined them together with the ampersand ( & ). But as you can see, the two words are actually joined as one. We can add a bit of space between the two words by using another ampersand. Change this lineFullName = FirstName & LastName to this:
FullName = FirstName & " " & LastName
What we're saying here is join this lot together: the variable called FirstName and a single blank space and the variable called LastName. When you've finished concatenating it all, store the result in the variable FullName.
Notice that we don't surround FirstName and LastName with quotation marks. This is because these two are already string variables; we stored "Bill" into FirstName and "Gates" LastName. So VB already knows that they are text.


Exercise

Remove one of the ampersand symbols (&) from this line in your code:
FullName = FirstName & " " & LastName
Move your cursor down a line or two. You should see that part of your code has a wiggly blue line under it:
Synatx error in VB NET
VB is telling you that it has problems with this line of code. If you hold your mouse over the wiggly blue line, VB tries to provide an explanation:
Error message
The explanations VB provides are sometimes enigmatic. But you will know that there is a problem. If you run the code, you'll get this popping up at you:
Build Erros in VB NET
Click the NO button. Put the ampersand back in, and all will be well.

Exercise B

Amend your code so that the textbox reads Gates Bill when the Command button is clicked.

Exercise C

Add another string variable to your code. The variable should hold a middle name. Display the first name, the middle name and the last name in the textbox.
Points to remember:
  • Your variable names cannot include spaces. So the variable MiddleName would be all right, but Middle Name will get you an error message
  • When you're putting text into your new variable, don't forget the two double quotes
  • Remember to put in enough ampersands in your FullName = line of code

Assigning Textbox text to your Variables

Instead putting direct text into your variables, such as "Bill" or "Gates", you can get text from a textbox and put that straight into your variables. We'll see how that's done now. First, do this:
  • Add a new textbox to your form
  • With the textbox selected, locate the Name property in the Properties area:
The Name property of the VB TextBox
The current value of the Name property is Textbox2. This is not terribly descriptive. Delete this name and enter txtLastName. Scroll down and locate the Text property. Delete the default text, and just leave it blank.
Click on your first textbox to select it. Change the Name property from Textbox1 to txtFirstName.
What we've done is to give the two textboxes more descriptive names. This will help us to remember what is meant to go in them.
Unfortunately, if you view your code (click the Form1.vb tab at the top, or press F7 on your keyboard), you'll see that the blue wiggly lines have returned:
Syntax error in NET
If you hold your cursor of the Textbox1, you'll see this:
Error Message
It's displaying this message because you changed the name of your Textbox1. You now no longer have a textbox with this name. In the code above, change Textbox1 into txtFirstName and the wiggly lines will go away. (Change it in your Button1 code as well.) Your code should now read:
txtFirstName.Text = FullName
Run your programme again. If you see any error messages, stop the programme and look for the wiggly lines in your code.
We'll now change our code slightly, and make use of the second textbox. You'll see how to get at the text that a user enters.
Locate these two lines of code
FirstName = "Bill"
LastName = "Gates"
Change them to this
FirstName = txtFirstName.Text
LastName = txtLastName.Text
Remember: the equals ( = ) sign assigns things: Whatever is on the right of the equals sign gets assigned to whatever is on the left. What we're doing now is assigning the text from the textboxes directly into the two variables.
Amend your code slightly so that the Whole Name is now displayed in a message box. Your code should now be this:
Dim FirstName As String
Dim LastName As String
Dim WholeName As String
FirstName = txtFirstName.Text
LastName = txtLastName.Text
WholeName = FirstName & " " & LastName
MsgBox(WholeName)
Run your programme. Enter "Bill" in the first textbox, and "Gates" in the second textbox. Then click your "String Test" button. You should get this:
the VB NET form
Before we changed the code, we were putting a person's name straight in to the variable FirstName
FirstName = "Bill"
But what we really want to do is get a person's name directly from the textbox. This will make life a whole lot easier for us. After all, not everybody is called Bill Gates! In the line FirstName = txtFirstName.Text that is what we're doing - getting the name directly from the textbox. What we're saying to Visual Basic is this
  • Look for a Textbox that has the Name txtFirstName
  • Locate the Text property of the Textbox that has the Name txtFirstName
  • Read whatever this Text property is
  • Put this Text property into the variable FirstName
And that's all there is too reading values from a textbox - just access its Text property, and then pop it into a variable.


Exercise

  • Add a third textbox to your form
  • Change its Name property to txtWholeName
  • Add labels to your form identifying each textbox (A quick way to add more labels is to use the toolbox to add one label. Then right click on that label. Choose Copy from the menu. Right click on the form, and select Paste.)
  • Write code so that when the "String Test" button is clicked, the whole of the persons name is displayed in your new textbox
When you complete this exercise, your form should look like this one (we've deleted the first button and its code, but you don't have to):
Your Form for this Exercise

More about Variables in VB NET

We've met two variable types so far - As String and As Integer. But there are quite a few more you can use. Let's start by examining number variables.
Start a new project for this. If you have the old one displayed, you can click File > Close Solutionfrom the menu bar. You will then be returned to the Start Page. Click the New Project button at the bottom. In the dialogue box, give your project a name.
Put a textbox and a Button on your new form. Change the Properties of the Textbox to the following
Name: txtNumbers
Font: MS Sans Serif, Bold, 10
Text: just delete the default Textbox1, and leave the textbox blank
Change the Properties of the Button to the following:
Text: Answers
Font: MS Sans Serif, Bold, 10
Click on the Form itself, and change it's Text property to "Testing Types". Your Form should look something like this:
A Form to test Variable Types
Double click on the Button to bring up the code window. Type the following code for your Button (The Button1_Click part is spread over three lines only for ease-of-reading on this web page. You can keep yours on one line in your code):
Private Sub Button1_Click(ByVal sender AsSystem.Object, _
ByVale As System.EventArgs) _
Handles Button1.Click
Dim testNumber As Short
testNumber = Val( txtNumbers.Text )
MsgBox testNumber
End Sub
Notice that there is a new Type of variable declared - As Short. This means "Short Integer". We'll see what it does. The Val part converts the Text into a number.
Run your programme. While it's running, do the following:
  • Enter the number 1 into the textbox, and click the Answers button
  • The number 1 should display in the Message Box
  • Add the number 2 to the textbox and click the Button
  • The number 12 should display in the Message Box
  • Add the number 3 to the textbox and click the Button
  • The number 123 should display in the Message Box
  • Keeping adding numbers one at a time, then clicking the button
How many numbers did you get in the textbox before the following error message was displayed? (Click Break to get rid of it.)
Overflow Error Message
You should have been able to enter 12345 quite safely. When you entered 123456 and clicked the button, that's when the error message displayed.
When you click the Break button, you are returned to the coding environment. You'll see the problem line highlighted in yellow:
Problem lines are highlighted in yellow
But your programme will still be running. So click Debug > Stop Debugging to return to the normal code window.
An Overflow happens when you try to put too much information into a variable that can't handle it.


The reason we got an error message after just 6 numbers was because of the variable type. We had this:
Dim testNumber As Short
And it's As Short that is causing us the problems. If you use As Short you're only allowed numbers up to a certain value. The range for a Short variable is -32 768 to 32 767. When we entered 6 numbers, Visual Basic decided it didn't want to know. If you run your programme again, and then enter 32768, you'll get the same Overflow error message. If you change it once more to -32769, you'll get the error message as well. So it's not just 6 numbers a Short Type can't handle - it's 5 numbers above or below the values specified.
So what's the solution? Change the variable Type, of course!
Change the variable to this
Dim testNumber As Integer
Now start the programme and try again, adding numbers one at a time to the textbox, and then clicking the Command button. How far did you get this time?
If you started at 1 and added the numbers in sequence, you should have been allowed to enter 1234567890. One more number and Visual Basic gave you the Overflow error message, right? That's because variable types with As Integer also have a limitation. The range you can use with the As Integer variable type is -2,147,483,648 to 2,147,483,647. If you want a really, really big number you can use As Long.
Dim testNumber As Long
But these will get you whole numbers. Leave your number on As Integer. Run your programme again and enter a value of 123.45 into your textbox. Press the button and see what happens.
VB will chop off the point 45 bit at the end. If you want to work with floating point numbers (the .45 bit), there are three Types you can use:
Dim testNumber As Single
Dim testNumber As Double
Dim testNumber As Decimal
Single and Double mean Single-Precision and Double-Precision numbers. If you want to do scientific calculations, and you need to be really precise, then use Double rather than Single: it's more accurate.
The As Decimal Type is useful when you want a precise number of decimal places. It's not as accurate as the Double Type, though.
In terms of the space used in the computer's memory, Short Types use 2 Bytes, Integer Types use 4 Bytes, Long Types use 8 Bytes, Single Types use 4 Bytes, Double Types use 8 Bytes, and Decimal Types use 16 Bytes.

Exercise

Write a programme to calculate the following sum.
0.123345678 * 1234
Use the Single Type first, then change it to As Double. Use a Message box to display the answer. Was the number rounded up or rounded down for the Single Type?


Using Variables in your VB NET Code

In this next section, we're going to learn how to transfer the contents of one textbox to another textbox. We'll also learn to transfer the text from a label to a textbox, and whatever was in the textbox we'll transfer it to a label. This will get us a little more practise with variables, and how to use them.
Ok, start a new Visual basic project. You should know how to do this by now, and what the design environment looks like. But you should have a plain grey Form on your screen. By default it will be called Form1.
Make sure the Form is selected (has it got the white squares around it?), and the click the Nameproperty in the Properties window. Change the Name of the form to frmVariables.
Changing the Name property of a VB NET form
Set the Text property of the Form to "Transferring information". You can choose any background colour you like for the form, or leave it on the default.
Put the following controls on the Form, and change their properties to the one's specified below (NOTE: lbl is short for label):
Textbox
Name: txtVariables
Font: MS Sans Serif, Bold, 10
Text Delete the default text "Text1" and leave it blank
Label
Name: lblTransfer
BackColor: A colour of your choice
Text: Label Caption
Font: MS Sans Serif, Bold, 10
Button
Name: btnTransfer
Text: Transfer
The height of your controls is entirely up to you.
If you double click your Button to bring up the code window, you will see that the first line of the code no longer says Button1_Click (etc). The first line should say this
Private Sub btnTransfer_Click (ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles btnTransfer.Click
End Sub
The reason it has changed is because you changed the Name property of the Button. The button now has the Name btnTransfer. If you wanted to, you could change the Name property back to Button1. Then when you double clicked the button, the code window would pop up and the first line would be Button1_Click(etc ).
What we're going to do now is to transfer the Text on the label ("Label Caption") to our empty textbox. And all with the click of a button.
As you'll see, there isn't much code.
Type the following into your code window:
Dim LabelContents As String
LabelContents = lblTransfer.Text
txtVariables.Text = LabelContents
Your code window should now look something like this:
The Transfer code
Now Run your programme and test it out. When you click on the "Transfer" button, you should see that the contents of the label will be inserted into the textbox:
VB Form shows what the transfer code does
But let's break the code down and see what's going on.


Dim LabelContents As String
Here is where we set up a variable called LabelContents. Because it will be holding text, we've used the variable type As String.

LabelContents = lblTransfer.Text
Here is where we put something into our empty variable. We changed the Name property of our Label from the default Label1 to lblTransfer. A Label has lots of properties you can manipulate. One of those properties is the Text property. After you typed the word "lblTransfer" and then typed a full stop, you probably saw a drop down box appear. Inside the box is a list of all the properties and Methods that a Label has. We wanted to manipulate the Text property of our label so we selected the word Text after the full stop. So we were saying "Access the value of the Text property of the label called lblTransfer, and put this value into the variable called LabelContents." Because our Text was ""Label Caption", the variable LabelContents now holds the text "Label Caption."

txtVariables.Text = LabelContents
Finally, we want to transfer whatever is in the variable LabelContents to the Textbox. Our Textbox is called txtVariables. Again, after typing the full stop the drop down box would appear, showing you a list of all the properties that a Textbox has. The one we're interested in is the Text Property. So we're saying, "Take whatever text is in the variable LabelContents, and transfer it to the Text property of the Textbox called txtVariables.
And with three lines of code we can transfer text from a label to a Textbox. But can we do it the other way round? Can we transfer whatever is in a Textbox to a Label? Well, sure we can.
Add another button to your form. Change its Name property from Button1 to cmdTransferToLabel, and change the Caption property to "Transfer To Label". Again, there's just three lines of code.
So double click your new button to bring up the code window. Then type in the following code:
Dim TextBoxContents As String
TextBoxContents = txtVariables.Text
lblTransfer.Text = TextBoxContents
Now, see if you can work out how it works. It's the same thing as the first three lines of code: set up a variable, transfer the Text property of the Textbox to the variable, transfer the variable to the Text property of the Label. Run your programme and test it out. Type something into the Textbox, and then click the "Transfer To Label" button.

Exercise E

A button also has a Text Property. Write code to transfer the Text property of a button to the Textbox. It's probably better for this exercise to create a new Button. Set its Name property to whatever you like. And give its Text Property a new value (The Text property will be Button1 by default) .
But the process is exactly the same as the two bits of code above - you should only need 3 lines of code for this exercise.
  • Set up a Variable
  • Transfer the Text property of the button to the variable
  • Transfer the variable to the Textbox

A Calculator Project in VB NET

In the next few pages, you're going to create a Calculator. It won't be a very sophisticated calculator, and the only thing it can do is add up. What the project will give you is more confidence in using variables, and shifting values from one control to another. So create a new project, call itCalculator, and let's get started.

Designing the Form

Let's design the form first. What does a calculator need? Well numbers, for one. A display area for the result. A plus sign button, an equals sign button, and a clear the display button.
Here's how our calculator is going to work. We'll have 10 button for the numbers 0 to 9. When a button is clicked its value will be transferred to a display area, which will be a Textbox. Once a number is transferred to the Textbox we can click on the Plus button. Then we need to click back on another number. To get the answer, we'll click on the equals sign. To clear the display, we'll have a Clear button.
If you haven't already, create a new project. Save it as Calculator. To your new form, first add ten Buttons (You can add one, then copy and paste the rest). The Buttons should have the following Properties:
Namebtn Plus a Number (btnOne, btnTwo, btnThree, etc)
Text: A number from 0 to 9. A different one for each button, obviously
Font: MS Sans Serif, Bold, 14
Next, add a Textbox. Set the following properties for the Textbox:
Textbox
Name: txtDisplay
Font: MS Sans Serif, Bold, 14
Text: Erase the default, Textbox1, and leave it blank
Three more buttons need to be added
Plus Button 
Name: btnPlus
Font: MS Sans Serif, Bold, 14
Text: +
Equals Button 
Name: btnEquals
Font MS Sans Serif, Bold, 14
Text: =
Clear Button
Name: btnClear
Font MS Sans Serif, Bold, 14
Text: Clear
When your form design is finished, it might look something like this:
Calculator form in NET
So if you wanted to add 5 + 9, you would click first on the 5. A 5 would appear in the textbox. Then you would click the + symbol. The 5 would disappear from the textbox. Next, click on the 9. The number 9 would appear in the textbox. Finally, click on the = symbol. The 9 would disappear from the textbox, and the answer to our sum would replace it. We would then click the Clear button to clear the display.

The Code for the VB NET Calculator

You might be thinking that all this is terribly complicated at such an early stage. But it isn't really. All we are doing is transferring the Text Properties from the Buttons to the textbox. And you already know how to do that. The number buttons don't do anything else. All the work is done with the Plus button and the Equals buttons. And there's only two lines of code needed for the Plus button, and three for the Equals button.
For this to work, though, a little word about Scope in VB NET.
So far, when you've set up a variable, you've set them up behind a Private Subroutine. Like this:
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles Button1.Click
Dim MyVariable As String
End Sub
Suppose you had another button on the form, Button2, and the code was this
Private Sub Button2_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles Button2.Click
Dim MyOtherVariable As String
End Sub
How can you access what's in MyVariable from Button2? The answer is, you can't. It's like two people sitting at desks in cubicles. Each person has written something on a piece of paper. They can't see into the other person's cubicle, only whatever is their own cubicle. So how do they share their information?
Well suppose there is a screen in front of them. A big screen. They can both see the screen in front of them; it's each other they can't see. What they could do is project their information onto the screen. Then one person could see what the other has written.
Similarly, in VB you can set up your variable declarations outside of the code for a Button. That way, more than one Button can see the code.
You can place your variable declarations right at the top of the code window, just beneath the line that begins "Public Class Form1". We'll set up two Integer variables there, total1 and total2:
The General Declarations area in VB NET
Now all the controls on your form can see these two variables. Those Buttons you set up can put something in them, and every button has the ability to see what's inside them.
(Incidentally, if you want to know how to add the line numbers from the image above, click onTools > Options from the menu at the top of Visual Studio Express. From the dialogue box that appears, click on Text Editor on the left. Then click on All Languages. From the area on the right, put a check in the box for Line Numbers.)

The 0 to 9 Buttons

The Buttons with the Text 0 to 9 only need to do one thing when the button is clicked - have their Text Properties transferred to the Textbox.
So double click the 0 Button and enter the following code:
Private Sub btnZero_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles btnZero.Click
txtDisplay.Text = btnZero.Text
End Sub
This code will transfer the Text Property of a Button called btnZero to the Text Property of a Textbox called txtDisplay.
Run your programme and try it out. When the programme is running, click the 0 button to see that it does indeed transfer the Text on the Button to the textbox
Except, there's a problem with that code. If you wrote similar code for all ten of your number buttons, the calculator wouldn't be right. Why is that? Have you spotted what's wrong? It's a good idea to set this book aside for a while and think about why this code on it's own wouldn't work. In fact you could write code for a few more of the number buttons and test it out.
What happens when you transfer the number 2 to the Textbox, and then click the number 3? The number 2 will disappear, to be replaced by the number 3. Which is all right if all you wanted to do was add up single numbers, but not much good if you actually wanted the number 23 in the Textbox. With this code, you could have either the number 2 in the Textbox or the number 3, but not both!
So how do we solve this problem? How do we fix it so that we can have two or more numbers appearing in our Textbox?
What we need is a way to get whatever is in the Textbox to stay where it is, and not disappear on us when we click a different number. It's quite easy. It's this:
txtDisplay.Text = txtDisplay.Text & btnZero.Text
So now we're saying the textbox doesn't just contain the Text on the Button. It must also keep whatever is inside the textbox as well.
So what you need to do now is to add that code to all of your ten number Buttons. Obviously it won't be exactly the same. For the button called btnOne the code would be this:
txtDisplay.Text = txtDisplay.Text & btnOne.Text
When you've finished coding all ten buttons, run the programme and click all ten number button to see if they do indeed transfer the numbers on the caption to the textbox. Not only that, but test to see if you can have more than one number in the textbox.
Now that we can get numbers into our Textbox display area, we'll write code to do something with those numbers - add them together, in other words.

Coding the Plus Button

To add up 5 + 9, we'd do this:
  1. Click first on the 5
  2. A 5 appear in the textbox
  3. Click the + symbol
  4. The 5 disappears from the textbox
  5. Click on the number 9
  6. A 9 appears in the textbox
  7. Click on the = symbol
  8. The 9 disappears from the textbox
  9. The answer to 5 + 9 appears in the textbox
  10. Click the "Clear" button to clear the textbox
We've done numbers 1 and 2 on that list. We're now going to do numbers 3 and 4 on the list. What we're trying to do is this: Click on the Plus symbol and make the number in the Textbox disappear. Before the number vanishes, we can store it in a variable. The variable we're going to be storing the number in is one of those variable we set up at the top of the code. It's this one:
Dim total1 As Integer
We've already seen how to retain a value from a textbox and add it to something else:
txtDisplay.Text = txtDisplay.Text & btnZero.Text
Here, we kept the value that was already in the textbox and joined it to the Text property of the button.
We can do something similar if we want to retain a value that is already in a variable. Examine this:
variable1 = variable1 + 1
The "= variable1 + 1" part just says "Remember what is in the variable variable1, and then add 1 to it. So if variable1 contain the number 3, what would variable1 now hold after that bit of code is executed? The whole code might be this:
variable1 = 3
variable1 = variable1 + 1
(If you don't know the answer to that, please send an email and ask for some further clarification on the subject.)
The above is known in programming terms as "Incrementing a variable". There is even a shorthand you can use:
variable1 += 1
This says "variable1 equals variable1 plus 1". Or "Add 1 to variable1". You can also use the other mathematical operators with the same shorthand notation:
variable1 = 10
variable1 *= 3
This new code says "Multiply whatever is inside of variable1 by 3".
The shorthand notation can be tricky to read (and to get used to), so we won't use it much. But it's there is you want it.


Back to our code.
If we're going to be adding two numbers together, we need Visual Basic to remember the first number. Because when we click the equals sign, that first number will be added to the second number. So if we haven't asked VB to remember the first number, it won't be able to add up.
The variable we're going to be storing the first number in is total1. We could just say this:
total1 = txtDisplay.Text
Then whatever is in the textbox will get stored in the variable total1.
Except we want VB to remember our numbers. Because we might want to add three or more numbers together: 1 + 2 + 3 + 4. If we don't keep a running total, there's no way for our programme to remember what has gone before, it will just erase whatever is in total1 and then start again.
So just like the code above (varaible1 = variable1 + 1), we need to "tell" our programme to remember what was in the variable. We do it like this:
total1 = total1 + Val(txtDisplay.Text)
That Val( ) part just makes sure that a number in a textbox is kept as a number, and not as text. It's short for Value. The important part is the total1 + txtDisplay.Text. We're saying "The variable total1 contains whatever is in total1 added to the number in the textbox." An example might clear things up. Suppose we were adding 5 + 9. Now, suppose total1 already contained the number 5, and that number 9 was in the textbox. It would work like this:
Finally, we need to erase the number in the textbox. To erase something from a textbox, just set its Text property to a blank string. We do this with two double quotation marks. Like this:
txtDisplay.Text = ""
That tiny bit of code will erase the Text a textbox. Another way to erase text from a textbox is to use the Clear method. After you typed a full stop, you probably saw the drop down list of Properties and Methods. Scroll up to the top, and locate the word Clear. Double click "Clear" and the drop down list will close. Hit the return key and VB adds two round brackets to your code:
txtDisplay.Clear( )
Notice that we're not setting the textbox to equal anything. We're using something called a Method. You can tell it's a Method because there's a purple block icon next to the word. A Method is a built-in bit of code that VB knows how to execute. In other words, it knows how to clear text from a textbox. You'll learn more about Methods later.
So the whole code for our Button called btnPlus is this:
Private Sub btnPlus_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles btnPlus.Click
total1 = total1 + Val(txtDisplay.Text)
txtDisplay.Clear()
End Sub
Add that code to your Plus button. All we've done with that code is to store numbers into our variable total1 and then erase whatever was in the textbox.
We now need to add the numbers up.

Exercise F

Write the code for the equals button. There's only three lines in total, and here's a little help.
You need to use the other variable that was set up at the top of the coding window, total2. The variable total1 will be added to whatever is total2
The first line of code will be this
total2 = total1 + (something missing here)
Your job is to supply the missing code. In other words, replace "(something missing here)"
Remember that total1 contains the first number to be added. And you know where that came from. The only thing left to do is to add the second number.
For the second line of code, you need to transfer the total2 variable to the textbox.
For the third line of code, all you are doing is resetting the variable total1 to zero. That's because after the equals button has been pressed, we have finished adding up. If you wanted to do some more adding up, that total1 will still hold the value from the last time. If you reset it to zero, you can start adding some new numbers.
The only thing left to do is to write a single line of code for the Clear button. All you are doing there is erasing text from a textbox. Which you already know how to do.
When you're finished, you should have a simple calculator that can add up integers.

The Message Box in VB .NET


The message box function you have used so far is the old message box function. It is the one left over form VB6:
MsgBox("Your Message Here")

The new VB.NET message box function is very similar, but the way you use it is slightly different. It's this:
MessageBox.Show("Your Message Here")
So you type the word "MessageBox" then a full stop. Double click the "Show" method on the menu the appears. Then type a round bracket. You should get a rather long and complex tool tip appearing. In fact, it's too long to even fit on this page!
What it all means is there are options you can use with your message box. The first one is "text As String". The text in question is the text that will appear for your message - the message itself, in other words. The next one is "caption As String". This sets the white caption at the top of the message box.
So if your message box function was this:
MessageBox.Show("This menu will Undo an Operation""Undo")
You would get this message box popping up:
An undo message box
Each option for your message box is separated by a comma. If you type a comma after the "Undo" in the code above, you'll get another pop-up menu. On this menu, you can specify which buttons you want on your message box:
Button options for your message box
If you only need the OK button on your message boxes, then double click this item, then type a comma. Yet another pop-up menu will appear. On this menu, you can specify the symbol that appear in the message box:
Add a symbol to your message boxes
It's up to you which symbol you choose. Experiment with all of them and see what they look like. In the image below, we've gone for the Information symbol:
The new Undo box has a symbol on it
Compare the message box above with the one we had earlier:
The earlier undo message box
In a real programme, you should use the new MessageBox.Show( ) function, rather than the MsgBox() we used (and will again because it saves on typing and space!)

Comments

Post a Comment