Visual Basic programming. Write your first .NET code

  • NSHIMIYUMWUNGELI Antoine Marie Zacharie

tiny_mce_marker_Two- Write your first .NET code

How to Create Variables in VB .NET

Why are we discussing variables? And what is a variable?z3

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 number 2 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:


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.


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:


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, too, if it becomes to long. But you don't have to.

No more reading these lessons online - get the eBook here!


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 means that no other part of the programme can see this code except for our button


Short for Subroutine. The "Sub" word tells VB that some code follows, and that it needs to be executed


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. Let's add our code, which we'll do on the next page.



The Text Property of a Control

In the previous section, you just designed a form and had your first look at the code window. 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 number 2 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:


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:


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.


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.)


No more reading these lessons online - get the eBook here!


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:


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!



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


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)


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.)

In the next part, we'll about a different kind of variable - a string variable.

String Variables

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:


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):


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 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 line FullName = 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.


No more reading these lessons online - get the eBook here!



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:


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:


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:


Click the NO button. Put the ampersand back in, and all will be well.


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


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

In the next part, we'll take a look at how to asign text from a textbox into our string variables.

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 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:


If you hold your cursor of the Textbox1, you'll see this:


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


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:

Pour être informé des derniers articles, inscrivez vous :
uburenganzira bwose bw'uru rubuga bwihariwe na Nshimiyumwungeri Antoine Marie Zacharie © 2014 -  Hébergé par Overblog