53
1 Visual Basic Welcome to the Visual Basic tutorials. Visual Basic (short-hand VB) is a programming language developed by Microsoft, it runs on the .Net Framework. With Visual Basic you can built Windows, Web and Windows Phone applications. Programs developed in Visual Basic will only run on a Windows Operating System (Well you can run them on Linux systems, but we are not discussing that!), Visual Basic is easy to learn, fun and powerful! The current tutorials are all tested with Visual Studio 2010 / 12 and use the .NetFramework 4. 4.5 will be able to support .NetFramework 4. These tutorials were written in .Net Framework 4.0, and I will continue to write them in 4.0. Visual Basic Installation To install Visual Basic you will need Visual Basic Express IDE, It can take a while to download and install, maybe about an hour or two depending on your internet speed, so while that is installing get yourself a snack!

Visual Basic Tutorial

  • Upload
    r-aj-an

  • View
    24

  • Download
    7

Embed Size (px)

DESCRIPTION

Sample VB Console Mode Tutorial for Beginners

Citation preview

Page 1: Visual Basic Tutorial

1

Visual Basic

Welcome to the Visual Basic tutorials. Visual Basic (short-hand VB) is a programming language

developed by Microsoft, it runs on the .Net Framework. With Visual Basic you can built Windows, Web

and Windows Phone applications. Programs developed in Visual Basic will only run on a Windows

Operating System (Well you can run them on Linux systems, but we are not discussing that!), Visual Basic

is easy to learn, fun and powerful!

The current tutorials are all tested with Visual Studio 2010 / 12 and use the .NetFramework 4. 4.5 will be

able to support .NetFramework 4.

These tutorials were written in .Net Framework 4.0, and I will continue to write them in 4.0.

Visual Basic Installation

To install Visual Basic you will need Visual Basic Express IDE, It can take a while to download and

install, maybe about an hour or two depending on your internet speed, so while that is installing get

yourself a snack!

Page 2: Visual Basic Tutorial

2

Visual Studio 2012 IDE

I am using Visual Studio Professional. Your environment may be a little different but not that

different.

Here is a basic overview of the Visual Studio 2012 Integrated development environment (IDE). It does

not go in to a full depth of the IDE just a short overview on the things we will be using.

Start Page

This is the start page of the IDE, on the right is a news feed from Microsoft (?) and on the left is your

recent projects and New and Open Projects. At the top is standard menu bar.

Page 3: Visual Basic Tutorial

3

New Project Window

This is the New Project window on the left you have installed languages and in the middle you have the

type of template. Windows, Web etc. (Note you will only see Visual Basic if you’re using the expression

edition) We will be making Console Applications on the .Net Framework 4.0! That is important to

remember!

Page 4: Visual Basic Tutorial

4

WorkSpace

Here is your workspace this is a console application. You have your work space (where you type code)

and your errors windows. Also if you see in the workspace I have line numbers to turn line numbers on

go to Tools > Options > (expand) Text Editor > VB > on the right hand side > Display, Line Numbers.

Tick it.

Note: The Visual Studio IDE changes frequently and it is hard to keep up with their software

updates, so advice you to also read the documentation as well.

Summary

The Visual Studio IDE is huge, there are a lot of features and I recommend you play around with it

familiarizing yourself. We will only use a few of these features in fact we will only be creating Console

Applications so we will hardly use anything advanced.

Page 5: Visual Basic Tutorial

5

Visual Basic Syntax

Visual Basic has a very simple programming syntax the language is not case-sensitive, so something like

Thecodingguys and are the same thing. The programming language is really for people new to the

programming world, and VB is the place to start since it is simple.

Go ahead and start a new VB Console Application, give it the name Syntax. You should see the following

code: Module Module1

Sub Main()

End Sub

End Module

Your code goes between the Sub Main() and End Sub. In VB lines does not end with a semi-colon or

anything, unlike C# and most other languages, VB is kept simple!

Comments Single line comments start with an apostrophe ' There are no block comments in VB XML comments start with three apostrophes, these are useful for documentation purposes

Organizing Code

Organizing code is very important, comments and regions are very useful. it is considered good practice

to group and comment your code so it's easy for other developers to work on it (No developer want's to

open a huge document with no comments!). Comments should provide a small description of that piece

of code. On the other hand regions are also useful use them to group code together. To create a region you

use the following syntax

#region "region name"

Other code here..

#End Region

You will see how useful regions can be in later tutorials.

Write Your First Program

Time to write your first program, between the Sub Main() and End Sub enter the following:

Console.WriteLine("My First Visual Basic Program!")

Console.ReadLine()

Hit F5, you should see the following print out

My First Visual Basic Program!

Console.WriteLine is a system method.

Page 6: Visual Basic Tutorial

6

the period (or dot) is called Member Accessor

Files

When you build your program certain files are created, it may seem a lot, but actually they are just simple

files and instructions for your program and the Visual Studio IDE. Navigate to C:\users\<yourname>\

Documents\Visual Studio\Syntax (or where ever you saved the work). In there is a file called Syntax.sln

and a folder called Syntax. If you open the Syntax.sln (sln is a Visual Studio Solution file) with notepad

you will just see it has some global settings, my advice to you is don't edit anything!

Open up the Syntax folder and in there will be 3 folders, obj, My Project and bin. There will also be two

files Module1.vb and Syntax.vbproj, open up the Module1.vb file and you will see that is just our source

code for our program. Then open up Syntax.vbproj which is just a Visual Basic Project File, it is actually

an XML file which stores information about other file locations do NOT edit it.

Now open up the bin folder in there is another folder called debug this is where your program will output.

If you double click Syntax.exe you will see the program run. Go back and open up the My Project folder

focus on the file called AssemblyInfo.vb this just stores information about the program such as author,

copyright, trademark etc..

Summary

Visual Basic has a very simple programming syntax most of the code is easily understandable, even if

you're not familiar with programming (that's why it's called Basic!). The language is not case-sensitive,

inline comments start with an apostrophe, XML comments start with 3 apostrophe's

Page 7: Visual Basic Tutorial

7

Visual Basic Variables

Variables allow us to store and retrieve data (It's a storage location and the data is held in the computers

memory (RAM)). In Visual Basic variables start with the Dim keyword.

Syntax Dim <variable name> As <data type>

VB supports a number of data types common ones are

Data Type Description

Integer Whole Numbers

Floating Point Numbers with decimals e.g. 5.2

Boolean True Or False

Double Floating Point numbers but more accurate

Char Single characters

Variables can start with upper-case or lower case characters.

Go ahead and create a new VB Console Application, name it Variables. Between the Sub Main() and End

Sub type the following.

Sub Main()

Dim myNumber As Integer

myNumber = 5

Console.WriteLine(myNumber)

Console.ReadLine()

End Sub

Hit F5 or click the green play icon on the toolbar. You should see the result 5.

Code Explained

First we use the Dim keyword to create the variable myNumber We then assign the value 5 to myNumber We then use the Console.WriteLine command to print out myNumber We then use Console.ReadLine to read that line.

String Variables are wrapped in quotation marks, comment out the above code highlight it all and press

CTRL+K+C (to uncomment, CTRL+K+U) Next type the following:

Dim name As String

Page 8: Visual Basic Tutorial

8

name = "Asim"

Console.WriteLine(name)

Console.ReadLine()

This should print out Asim. This code works same as above but just this time it was a string data type.

You can also add, subtract and perform other mathematical calculations. Under the above code write the

following:

Dim x As Integer

Dim y As Integer

x = 32

y = 15

Console.WriteLine(x + y) 'Add x (32) and y(15) ( 32 + 15 = ?)

Console.ReadLine() ' ReadLine

You should get the value 47. This time we made two integer variables called x and y assigned them a

value, then added them together.

Summary

Variables start with the Dim keyword Variables can start with upper-case or lower-case characters

Page 9: Visual Basic Tutorial

9

Visual Basic Strings

Strings are enclosed in double quotes ( " " ) Strings are a data type Strings are a collection of characters

Syntax

Dim stringName As String

Example

I will show you several ways in which you can manipulate strings. Create a new VB Console Application

and name it Strings next type the following:

Sub Main()

Dim myName As String

myName = "thecodingguys"

Console.WriteLine(myName)

Console.ReadLine()

End Sub

Press F5 to debug and you should see the text thecodingguys. This is a simple string. Comment out the

above code (CTRL+K+C)

Escape Character

At times you need to escape quotation marks which get in the way, see the following example.

Dim text As String

text = "Asim Said: "Hello World" "

Console.WriteLine(text)

Console.ReadLine()

If you run this (F5) you will get an error saying End of Statement expected the problem is that VB thinks

that the line ends at "Asim Said: " but it does not so what we need to do is put four double quotes around

hello world, so it should look like this:

Dim text As String

text = "Asim Said: ""Hello World"" "

Console.WriteLine(text)

Console.ReadLine()

Page 10: Visual Basic Tutorial

10

Output Asim Said: "Hello World"

New Line

At times you may need a new line, in C# the new line is simply \n however in VB it is quite different.

Comment out the above code and put this below.

Dim newLine As String

newLine = "This is a new" & vbCrLf & "Line"

Console.WriteLine(newLine)

Console.ReadLine()

This time we use the keyword vbCrLf to make a new line, You first put your first line code in one quotation

then your second in another and in between put & vbCrLf &

Concatenation

Concatenation is joining two things together in this case joining strings. It can be very useful at times

when you want to link something together to form a sentence. You use the & ( or + ) to form concatenation.

Take this one for example:

Console.WriteLine(myName & " is awesome")

This will print out "thecodingguys is awesome" myName is a variable we created earlier.

String.Format

The string.format method is useful for formatting your text you can format it in many ways. For example

say you wrote Console.WriteLine ("Your balance is £5"); the thing is if you gave this away to someone

in USA or Italy they would see the British pound symbol and not their own country currency symbol. This

is where the .Net Framework comes it hand, it can detect the users country / regional settings and format

the piece of text to match their regional settings.

Example Dim myNumber As Double = 158

strFormat = String.Format("{0:C}", myNumber)

Console.WriteLine(strFormat)

Console.ReadLine()

Now when you debug this (F5) you should see it print out 158 with your country currency symbol in front

of it. There are many more ways of formatting strings, below is a table which shows this.

Format Description

{0:C} Currency Symbol

{0:P} Percentage Symbol

Page 11: Visual Basic Tutorial

11

{0:N} Thousand Separator

The 0 in the format key specifies the parameter you want to format, followed by a colon and then the

formatting type.

Example 2

This time we use two parameters.

Dim myNumber As Double = 158

Dim mySecondNumber As Integer = 25

strFormat = String.Format("{0:C} {1:P}", myNumber, mySecondNumber)

Console.WriteLine(strFormat)

Console.ReadLine()

In this example the first parameter (myNumber) would appear as £158 and the second one would appear

as 25%

Manipulating Strings

There are many built in methods available to you, so you can format strings in a number of ways, for

example you can format a string and make it all upper-case, you can remove spaces, or you could simply

count the length of the string. In the next few examples I will show you how to manipulate strings, there

are many methods available so I can’t go through all of them, but go through the ones which will be useful

to you.

In the following examples I will be working with a string called, yourMessage which will have the text

“Welcome to thecodingguys” and another string finalResult which is set to nothing.

Dim yourMessage As String = "Welcome to thecodingguys"

Dim finalResult As String = Nothing

For the sake of brevity I have omitted the Console.WritelIne(finalResult), from the examples, however

you can always add it, just remember to add the Console.ReadLine() as well.

ToUpper and ToLower

The ToUpper and ToLower converts a string either to upper-case or lower-case (but I guess you already

figured that out)

Example finalResult = yourMessage.ToUpper()

finalResult = yourMessage.ToLower()

Page 12: Visual Basic Tutorial

12

Replace

The replace method, replaces a string with another string, it takes two parameters, old string and new

string, it can also take chars. In the following example the spaces in yourMessage are removed and

replaced with dashes.

finalResult = yourMessage.Replace(" ", "-")

Output Welcome-to-thecodingguys

Substring

The substring method can be used to return parts of a string, for example from the yourMessage string we

can return the first 5 characters only. The substing method takes two parameters the start index and length

index as integer.

Example finalResult = yourMessage.Substring(0, 7)

The 0 specifies the start point in this case it is at the beginning, the 7 specifies how many characters we

want from the starting point. To get all the characters you would do this:

finalResult = yourMessage.Substring(0, yourMessage.Length)

Output Welcome

Exceptions: Watch out for the ArguementOutofRangeException which is common, this occurs when

the string length is shorter than the points specified, for example if I did 0, 25 it would give that

exception as yourMessage is only 24 characters long.

Count

The count and length method return the length of the string

finalResult = yourMessage.Count()

Page 13: Visual Basic Tutorial

13

There are many more methods available.

Method Description Output

Contains See if a string contains a certain piece of text Reutrns boolean (either true of false)

StartsWith See if a string starts with a certain piece of text Boolean - true of false

EndsWith See if a string ends with a certain piece of text Boolean - true of false.

Summary

In this tutorial you learned how to format, and manipulate strings in Visual Basic.

New Line is vbCrLF Escape Character "" String.Format followed by {0:C} or N or P. (String.Format Full List is at MSDN Library VB String Formats) Functions: ToUpper, ToLower, Replace, Substring, and 1000s more!

Page 14: Visual Basic Tutorial

14

Visual Basic Dates And Times

Dates and Times are also another data type in Visual Basic. You might at times need to print out the date

in your application or web application, like shown at the bottom you can see the last edit date and time.

There are many ways you can manipulate dates and times in Visual Basic we will discuss the most

common ones. Create a new VB console application and name it Dates And Times. Then between Sub

Main and End Sub() put the following code:

Console.WriteLine(DateAndTime.Now)

Console.ReadLine()

This will output the date and time like this:

17/07/2012 19:39:06

This will print out the date and time according to your PC, nothing really interesting. One thing you should

bear in mind is that since this is based on the .Net Framework the date and time will print out depending

on the format the computer uses since I am in the UK our format is dd/mm/YYYY and the time is 24 hour

clock if you’re in USA I think it is mm/dd/YYYY. The above code simply prints out the current date and

time.

Getting the date

This time we will just focus on getting the date and then formatting it in several ways. We are going to do

the same thing as before but this time we are just going to say Date.Now. Copy the following:

Console.WriteLine(Date.Now.ToLongDateString)

Console.ReadLine()

This prints out the date in a long format so its 17 July 2012 it will not print out the time as we have not

told it to. We can also print "short date" but using ToShortDateString. Try it remove the ToLongDateString

and replace it with ToShortDateString or simply copy the following:

Console.WriteLine(Date.Now.ToShortDateString)

This will output 17/7/2012

Extract date

This time we will get just the month and day on its own. Since the Date will be displayed as a Integer we

will need to convert it to a string and format it, for example take a look at this:

Console.WriteLine(Date.Now.DayOfWeek)

Now this surprisingly outputs 2 (for humans that means Tuesday ) because Tuesday is the second day of

the week. However what about if you wanted the word "Tuesday" ? In this case we need to format it. What

we do is write Day.Now.ToString(format) as follows:

Console.WriteLine(Date.Now.ToString("dddd"))

Page 15: Visual Basic Tutorial

15

This will simply print out the current day. You can do the same for month simply put MMMM instead of

dddd (Correct casing). Getting the year is also pretty simple we use this code:

Console.WriteLine(Date.Now.Year)

This will print out the current year (Currently it's 2012). Now we are going to focus on the AddDays

Method, this simply adds days to the current day. For example today is 17/07/2012 if you wanted to know

what the day was in the 30 days you write this:

Console.WriteLine(Date.Now.AddDays(30))

Today is 17 July 2012, and in 30 days it will be 16 August 2012. This also works for AddHours,

AddMinutes, AddYear, AddSeconds and many more.

Getting the time

This time we will get the time on its own. We do the same thing as we did before when we got the date

but this time we will use ToLongTimeString. Like this:

Console.WriteLine(Date.Now.ToLongTimeString)

This will print out the current time, it will print out the hours, minutes and seconds. You can also use the

ToShortTimeString method this will only get the hour and minute. Try it. Another thing you might want

to do is only get the date in 12 hour clock this is how you can do that:

Console.WriteLine(Date.Now.ToString("hh:mm:ss tt"))

This gets the time in 12 hour format and also displays AM or PM.

Extract time

Like the date we can also extract the time and get the hours and minutes on their own. It's basically same

as above.

Hour Console.WriteLine(Date.Now.Hour)

Nothing really much to explain it will simply get the hour, no minutes or seconds.

Minutes Console.WriteLine(Date.Now.Minute)

Seconds Console.WriteLine(Date.Now.Second)

Like before we can also add on hours like the following example.

Page 16: Visual Basic Tutorial

16

Console.WriteLine(Date.Now.AddHours(10).ToLongTimeString)

You can also get the minutes and seconds like before. In this example after we given the hours to advance

by (which is 10) we also add which time format we want this is because if we don't it will print out the

date and time!

Method / Property Name Description

ToLongDateString Prints out the day in the following format 17 July 2012

ToShortDateString Prints out the date is short format 17/7/2012

ToLongTimeString Gets the current time in the format HH:MM:SS (Hours, Minutes, Seconds)

ToShortTimeString Gets the current time in the format HH:MM (Hours and Minutes)

Now Gets the current date and time

Day Gets the current day as Integer.

Year Gets the year

Month gets the month as Integer

DayofWeek Gets the day of the week as Integer.

Hour Gets the current hour

Minute Gets the current minute

AddHours Adds hours to the current time

AddDays Adds days to the current day

AddMonth Adds months to the current month

AddYear Adds Year to the current year

For more information on these go to http://msdn.microsoft.com/en-us/library/03ybds8y

Summary

Dates and Time are easy to use in Visual Basic, this tutorial gave you a starting point, there are many ways

you can format and manipulate the date. Date and Time are a data type and remember if you are going to

do some calculations based on the date and time it is best to use DateTime.UtcNow.

Page 17: Visual Basic Tutorial

17

Visual Basic Math

Computers are good with numbers, well they are numbers nothing but 0 and 1. ( 0 meaning off 1 meaning

on). Since they are good with numbers it's obvious they can perform mathematical calculations such as

adding, subtract, square root, and also cos, sin, tan, and hyp. (Before you ask what's that? That's

actually Pythagorean Theorem). There are at times problems, for example 2 + 6 * 5 now you might think

the answer for this is 40 ( 2 + 6 = 8 * 5 = 40 ) in fact it is 32, when something like this happens the

Multiplication or Division is always done first. You can force 2 + 6 to be calculated first by putting

brackets around it like this:

Console.WriteLine((2 + 6) * 5)

Console.ReadLine()

Now the answer you should get is 40.

Another example is when there is Multiplication and Division then which one is done first? Well it will

just start from the left to right, for example take this example

Console.WriteLine(30 / 2 * 3)

Console.ReadLine()

The answer for this is 45. Since we got both Division and Multiplication it just starts from the left, you

can again force 2 * 3 to be done first by putting brackets around it, then the answer would be 5.

Division

With Division you can format the result, take this one for example,

Dim Divide As Integer

Divide = 5

Console.WriteLine(9 / Divide)

Console.ReadLine()

It will output 1.8. We can force this to a integer value by using CType function. So it would look like

this:

Dim Divide As Integer

Divide = 5

Console.WriteLine(CType(9 / Divide, Integer))

Console.ReadLine()

This time we use the CType function then at the end specify the data type which is integer, the result of

this is 2. It is converted to the nearest whole number. ( 1.8 to the nearest integer is 2)

Page 18: Visual Basic Tutorial

18

Short Hand Math

You can use a much simpler way to do arithmetic. like the following.

Dim Shorthand As Integer

Shorthand = 5

Shorthand += 8

Console.WriteLine(Shorthand)

Console.ReadLine()

In this case we assign Variable Shorthand the value 5 then add 8 but just move the operator to the left of

the equal sign. This works for addition, subtraction, multiplication but not division since the result can be

a decimal value.

Other Math Functions

You can also find square roots, power and round. To do this first right at the top where it says Module

Module1 above that put Imports System.Math. Then right the following:

Console.WriteLine(Sqrt(8))

Console.ReadLine()

This finds the Square root of 8. Which is 2.828.......

Finding the power of 10 and 5

Console.WriteLine(Pow(10, 5))

Console.ReadLine()

The answer is 100,000

Rounding

Console.WriteLine(Round(8.7))

Console.ReadLine()

This rounds to 9. (Do not confuse this with Rnd that is Random)

There are many more math functions that can be done the .Net Framework is a big library for more info

see the MSDN reference.

Summary

Multiplication and Division are always done first If there are both Multiplication and Division it will start from left to right Short Hand Math put the operator on the left hand side of the = sign To use math functions such as sqrt, pow, round, make sure you import system.math

Page 19: Visual Basic Tutorial

19

Visual Basic Operators

Equality Operators

Operator Description Example

= Is equal to x = y

NOT NOT equal to

if NOT x = y Then

End If

Relational Operators

Operator Description Example

< Less than if y < x Then

End If

> Greater Than if x > y Then

End If

<= Less than but equal to if x <= y Then

End If

>= Greater than but equal to if y >= x Then

End if

Conditional Operators

Operator Description Example

AND Compare two variables if a AND

b equals

If x AND y Then

End If

OR Compare two variables if a OR b

equals

If x or y Then

End If

Page 20: Visual Basic Tutorial

20

Arithmetic Operators

Operator Description Example

+ Addition Operator 5 + 5

/ Division Operator 10 / 5

* Multiplication Operator 10 * 8

Other Operators

Operator Description Example

& Concatenation "a" & "b"

These are common operators, you should learn all of them.

Page 21: Visual Basic Tutorial

21

Visual Basic If Statement

If you have programmed before in languages like C#, PHP, or JavaScript then you will be familiar with if

statements. For those of you who haven't an if statement is simply a decision statement, the code contained

inside it will execute if the condition evaluates to true.

Syntax

If condition Then

'Your code here..

End If

Tip in the VS studio IDE if you type if until it's highlighted then hit tab twice the syntax will

automatically be inserted.

Create a new VB Console Application and name it If Statements. Then copy the following.

Sub Main()

Dim age As Integer

Console.WriteLine("Please enter your age")

age = Console.ReadLine().ToString()

If age = 15 Then

Console.WriteLine("You are not old enough to drink")

End If

Console.ReadLine()

End Sub

Code Explained:

First we created a variable called age with the data type integer We then print to the console "Please enter your age" We then read the users value if you enter 15 you will see the message "You are not old enough to drink" If you enter any other value your computer will explode… just kidding nothing will happen and the

program will terminate.

This is a simple if Statement the problem with this if statement is that if condition evaluates to false (so

age is not 15) the program simply won't do anything. In this case we can use an If Else statement.

If Else

Syntax If condition Then

code

Else

Page 22: Visual Basic Tutorial

22

other code

End If

Comment out the other If Statement (CTRL+K+C) then copy the following code:

Dim username As String

Dim password As Integer

username = Nothing

password = Nothing

Console.WriteLine("Enter Your UserName")

username = Console.ReadLine()

Console.WriteLine("Enter Your Password")

password = Console.ReadLine()

If username = "Asim" And password = 243 Then

Console.WriteLine("Welcome Asim!")

Else

Console.WriteLine("Access is denied")

End If

Console.ReadLine()

This seems a little more complex, but it is similar to the above if Statement you have two variables

(string/integer) which we use to store the values the user enters when promoted. Then we compare those

values to the values in our if statement so if username = "Asim" AND password = 243, then "Welcome

Asim" is displayed otherwise "Access denied" is displayed. You are also using the logical

operator And which you will learn about soon.

Nested If Else

You can also have nested If Else Statement.

Dim message As String

message = "Welcome " & username

If username = "Asim" And password = 243 Then

Console.WriteLine(message)

Else

If username = "Dave" And password = 12345 Then

Console.WriteLine(message)

Else

If username = "Admin" And password = 2012 Then

Console.WriteLine(message)

Else

Console.WriteLine("Oops could not find you!")

End If

End If

End If

This time we are doing the same thing as before, but we got more decisions. However, I made a new string

variable called message this was made to avoid repetition of writing the console message. Then we have

our if else statement it will see if the statements are true if it is it will print out the correct message if it is

Page 23: Visual Basic Tutorial

23

false it will print the last message. If Else statements can become really long so it is best to use a Select

Case Statement which we will cover in the next lesson.

If Else Statement Operators

There are a few operators you can use with if else statements, the table below shows the operators.

Operator Description Example

< Less than operator if 19 < 20 Then

> Greater than operator if 20 > 19 Then

= Equal to operator if a = b Then

<> Not equal to operator if a <> b Then

<= Less than or equal to operator if 19 <= b Then

>= Greater than or equal to operator if 19 >= b Then

Example Less than If 15 < 20 Then

Console.WriteLine("15 is greater than 20!")

End If

Console.ReadLine()

In this short example the condition is simply asking "Is 15 less than 20?" since it is (so its true) the if

statement will proceed execution.

Example Not equal to Dim name As String

name = "Adam"

If name <> "Asim" Then

Console.WriteLine("Name does not equal Asim, Name = " + name)

End If

Console.ReadLine()

In this example the condition is saying "if name NOT EQUAL TO Asim". Just remember that name (the

variable) does not equal Asim so the condition is true and the if statement will execute.

Page 24: Visual Basic Tutorial

24

Logical Operators

You can use the logical operators to extend the if else statements and use two conditions for example if a

= b And a > 19 Then

Operator Description

And And Operator - If both conditions are true, then result is true

Or Or Operator - If either of the conditions is true the result will be true

Not Not Operator - If the condition is false then the result will be true, or vice versa.

Example Logical And Operator Dim a As Integer

Dim rnd As New Random

a = rnd.Next(90, 160)

If a > 100 And a < 150 Then

Console.WriteLine("A is greater than 100, but less than 150, A = " + a.ToString())

End If

Console.ReadLine()

This example may seem quite confusing, but it is not the only difference here is that I am using the Random

class to generator a random number between 90 - 160 which is assigned to the variable a. Then the if

statements condition is, "Is a greater than 100 AND less than 150?" If it is it will continue to execute the

if statement otherwise it will terminate.

Summary

In this tutorial you have learned about if statements, if else statements and nested if else statements You

have also learned how to use the Conditional and Logical operators to perform more actions based

on several conditions.

Page 25: Visual Basic Tutorial

25

Visual Basic Select Case

If you have programmed before in C# or PHP you might be familiar with the Switch Statement, in VB the

Switch Statement is called the Select Case. Select Case statements are just like If Else Statements but have

a few differences, they only evaluate one thing and are more readable.

Syntax Select Case VariableName

Case 1

Case 2

Case Else

End Select

Let’s take a look at an example, first create a VB Console Application name it Select Case, then copy the

following.

Dim game As String

Console.WriteLine("Your favourite game?")

game = Console.ReadLine()

Dim message As String

message = game & " is your favourite game!"

Select Case game

Case "GTA 4"

Console.WriteLine(message)

Case "Battlefield 3"

Console.WriteLine(message)

Case "GRID"

Console.WriteLine(message)

Case "Infamous"

Console.WriteLine(message)

Case Else

Console.WriteLine("Looks like your game is not on my list")

End Select

Console.ReadLine()

In the above example we collect the users input and simply compare it through the case labels if it matches

any labels the code for that case label will execute, otherwise the Case Else will execute.

Page 26: Visual Basic Tutorial

26

Case Sensitive

The issue with the above example is that the case labels are case sensitive so if you typed "gta 4" as your

favourite game the Case Else will execute as "gta 4" is not in our case label, although it actually is, but is

all upper-case, we can solve this issue by using the ToLower() method.

Dim game As String

Console.WriteLine("Your favourite game?")

game = Console.ReadLine()

Dim message As String

message = game & " is your favourite game!"

Select Case game.ToLower()

Case "gta 4"

Console.WriteLine(message)

Case "battlefield 3"

Console.WriteLine(message)

Case "grid"

Console.WriteLine(message)

Case "infamous"

Console.WriteLine(message)

Case Else

Console.WriteLine("Looks like your game is not on my list")

End Select

Console.ReadLine()

Nothing much has changed accept we have added the ToLower() method to our variable name, we also

changed the case labels all to lower-case, this is because when the case label compares it, it essentially

compares "gta 4" to "gta 4" the users input will all be lower-case so even if the user types "gTa 4" it will

be converted to lower-case, and therefore the case labels need to be lower-case so they can be compared.

The case else is there because if the other cases don't match then that message appears.

Select Case - Using Operators

You can use these operators in your case labels.

Operator Description

< Less than

> Greater than

<= Less than or equal to

>= Greater than or equal to

<> Not equal to

= Equal to

Page 27: Visual Basic Tutorial

27

When using operators you need to use the Is or To keyword. So the case label would look like this:

Case Is > 10

Case 13 To 20

The case label translates to "Is Greater than 10?" and the second translates to "Is between 13 and 20". Now

it is pretty obvious that you can only use the relational operators if you are evaluating an integer or double.

Example Dim age As Integer

Console.Write("Please enter your age")

age = Console.ReadLine()

Select Case age

Case Is < 17

Console.WriteLine("You are not old enough to drink alcohol")

Case Is >= 18

Console.WriteLine("You are old enough to drink alcohol, but drink

carefully!")

Case Else

Console.WriteLine("Didn't understand that")

End Select

Console.ReadLine()

In this example I used the greater than and greater than or equal to operator to match the users input. The

basic example takes the input from the user and then compares it to the case labels.

Example - Using To Keyword Dim age As Integer

Console.Write("Please enter your age")

age = Console.ReadLine()

Select Case age

Case 10 To 17

Console.WriteLine("You are not old enough to drink alcohol")

Case 18 To 50

Console.WriteLine("You are old enough to drink alcohol, but drink

carefully!")

Case Else

Console.WriteLine("Didn't understand that")

End Select

Console.ReadLine()

This example is similar to the above one, however, this time we are using the To keyword and comparing

between a range of numbers.

Page 28: Visual Basic Tutorial

28

Example - Strings

In the above example we used integer this time we will use strings and use the <> operator.

Dim car As String

Console.WriteLine("Enter your favourite car")

car = Console.ReadLine()

Select Case car.ToLower()

Case Is <> "audi"

Console.WriteLine("It's not an audi!")

Case Else

Console.WriteLine("It was an Audi!")

End Select

Console.ReadLine()

Similar to the above statements this time we use a string.

Summary

In this tutorial you learned about using the Select Case in Visual Basic, you learned about the operators

you can use and also how to deal with case sensitivity issues.

Page 29: Visual Basic Tutorial

29

Visual Basic For Next

The For Next loop (or For Iteration) loops through data. It can be very useful when looping through lists.

Syntax For index = 1 To 10

Next

we're going to perform a small loop printing the numbers 1 to 50 on the screen.

For i = 1 To 50

Console.WriteLine(i)

Next

Console.ReadLine()

When you debug this you should see it print out 1 to 50 on the screen.

Using Step Keyword

In the above example the numbers print out from 1 to 50 incremented by 1 each time. However, you can

use the step keyword and increment by 3, 7, 8 or any other number each time.

Example

For myNumber As Integer = 1 To 50 Step 5

Console.WriteLine(myNumber)

Next

Console.ReadLine()

In this example we do two different things. First we declare a variable called myNumber and set data type

as integer, but without using the Dim keyword. We use the For keyword to make the variable that means

this variable is local to this For Loop Statement. This is a inline Variable. Next you print out 1 to 50 but

we increment by 5 each time.

Looping Backwards

You can also loop backwards similar to the example above.

Page 30: Visual Basic Tutorial

30

Example For myNumber As Integer = 50 To 1 Step -5

Console.WriteLine(myNumber)

Next

Console.ReadLine()

This time we are going backwards notice how we put a negative sign in front of the 5. You should get the

numbers 50, 45 40... print out.

Of course you don't have to print out numbers it can be anything such as words, or other data. A good

example of this is when filling out online forms, in online forms sometimes you get a drop-down list

asking you to select the year, you really think someone types all those? It is done server side and they only

need one piece of code like above.

Example - Get System Fonts

Before we begin this you need to reference the System.Drawing.Text above Module put this:

Imports System.Drawing.Text

Then in the solution explorer right click on your project name and click on Add Reference, make sure you

have selected Framework on the left hand side (if using VS 2012) look for System.Drawing.Text and

make sure it is ticked. Now copy this;

Dim fonts As New InstalledFontCollection()

For fntFamily As Integer = 0 To fonts.Families.Length - 1

Console.WriteLine(fonts.Families(fntFamily).Name)

Next

Console.ReadLine()

This will print out all the fonts to the console.

Summary

In this tutorial you learned about the For Next Loop and learned how to use the step keyword, and loop

backwards. For statements are useful to print out large amounts of data like years, days, months.

Page 31: Visual Basic Tutorial

31

Visual Basic While Statement

The while statement evaluates something which is true, and it will keep looping until false.

Syntax While True

End While

Go ahead and create a new VB Console and name it While Statement. Copy the following:

Dim mynum As Integer

mynum = 25

While mynum < 100

mynum = mynum + 1

Console.WriteLine(mynum)

End While

Console.ReadLine()

You will just see a list of numbers from 26 to 100. We used the less than operator in this example, the

condition simply says "while 25 is less than 100". It will increment 25 by 1, once 25 = 100 it will stop as

the condition becomes false.

While mynum < 100

mynum = mynum + 1

Console.WriteLine(mynum)

If mynum = 51 Then

Exit While

End If

End While

This is similar to the above statement however, the statement will stop executing once it reaches 51. The

End While is required as it terminates the while block once the condition is false. The Exit While stops

execution immediately and continues to the next statement.

Exiting Loop

You can use the Exit While statement to stop the loop once some condition is met, in

the following example We ask the user for their age and increment by 1 until it reaches 5000 then exit the

loop.

Dim age As Integer

Console.WriteLine("enter age")

Page 32: Visual Basic Tutorial

32

age = Console.ReadLine()

While age > 10

age += 1

Console.WriteLine(age)

If age = 5000 Then

Exit While

End If

End While

Console.ReadLine()

In this simple example we ask the user for their age, and if it is greater than 10 we increment it until it

reaches 5000, we use an if statement to see if age equals 5000, if it does we Exit the While Statement.

Operators

You can use these operators in a while statement.

Operator Description Example

< Less than While 10 < 20

> Greater than While 20 > 10

<= Less than or equal to While 20 <= 15

>= Greater than or equal to While 20 >= 15

= Equal to While age = 20

<> Not equal to While age <> 10

Read a file

Create a text file and name it note.txt, insert some content and save in on the desktop. Next insert this

above Module Module1

Imports System.IO

This imports the Input / Output namespace which allows us to read and write files.Below that add this:

Dim path = "U:\users\Asim Rehman\desktop\note.txt"

Dim sr As New StreamReader(path)

Dim line = sr.ReadToEnd()

Page 33: Visual Basic Tutorial

33

While line IsNot Nothing

Console.WriteLine(line)

Exit While

End While

Console.ReadLine()

Code Explained

You first need to import the namespace System.IO (it has the streamreader/writer class) Then you set your path as a string Intialize the string sr Create a new string line which reads the file to the end Next you have your while statement which has IsNot Nothing - This make sure the file is not empty Print out the file contents to the end Exit the while statement If you do not exit the while statement, the while statement will keep looping

Summary

In this tutorial you learned how to use Visual Basic while statements, you learned how to

loop through numbers, how to read a text file and also how to exit a loop.

Page 34: Visual Basic Tutorial

34

Visual Basic Do Loops

There are two Do Loops in Visual Basic the Do While and Do Until. The Do While loops something

which is true. The Do Until Loops until a certain condition is met. Create a New VB Console Application

name it Do Loops.

Do Until Dim myNumber As Integer = 0

Do Until myNumber = 5

Console.WriteLine("Pick a number between 1 and 6")

myNumber = Console.ReadLine()

If myNumber = 5 Then

Console.WriteLine("Yes 5, it is!")

Else

Console.WriteLine("Oops that's not the lucky number!")

End If

Loop

Console.ReadLine()

Code Explained

First we make a integer and call it myNumber and set it's default value to 0. Then we got a Do Until Statement which loops until myNumber = 5 Next we ask the user to pick a number between 1 and 6 we read the users value and store it in myNumber If the number is not 5 then they get the text "Oops that's not the lucky number" If they don't pick 5 then the question will be asked again. (It will keep looping until myNumber is 5, it's

an infinite loop) If they pick 5 then they will get the message "Yes 5, it is!" The program will close after this.

Do While

The Do While is similar to the Do Until but it evaluates something which is true.

Example Dim mySecondNumber As Integer

Do While mySecondNumber < 50

mySecondNumber += 1

Console.WriteLine(mySecondNumber)

Loop

Console.ReadLine()

Page 35: Visual Basic Tutorial

35

Code Explained

First we make a integer called mysecondNumber We use the Do While Loop and see if mysecondNumber is less than 50 (which it is, so it's true) we then increment it by 1 until it reaches 50 (then the Do While will become false)

Operators

You can use the following operators on Do Until and Do While

Operator Description

< Less than

> Greater than

<= Less than or equal to

>= Greater than or equal to

<> Not equal to

= Equal to

Loop While and Loop Until

It is possible to place the While and Until after the loop so it would be like this:

Dim myNumber As Integer = 0

Do

myNumber += 1

Console.WriteLine(myNumber)

Loop While myNumber < 10

Do

myNumber += 1

Console.WriteLine(myNumber)

Loop Until myNumber = 10

Console.ReadLine()

In this example the Until and While are after the Loop. The code will always execute at least once. Now

with this code if you run it, it will crash and give an overflowException, the first Loop While will execute

and it will keep going until myNumber is 10, then it will exit. The Do Until Loop will then execute and

this will keep looping (infinite) because myNumber is no longer equal to 10 it is 11 since the Do Loop

Page 36: Visual Basic Tutorial

36

executed once and myNumber += 1 changed its value to 11 and therefore this loop will execute until it

reaches 10, but it won't!

It is best to stick with Do While and Do Until instead of putting the While and Until after the loop, because

they will always execute no matter what. The Do While/Until would not execute if its condition is false.

Issues like the above example cause bugs in your application since the variable changed.

Example Dim myNumber As Integer = 0

Do

myNumber += 1

Console.WriteLine(myNumber)

Loop While myNumber < 10

Do Until myNumber = 10

myNumber += 1

Console.WriteLine(myNumber)

Loop

Console.ReadLine()

This is similar to the example above, however this time when the first loop executes and reaches 10 the

second loop will not execute because myNumber is already 10.

Summary

In this tutorial you learned about the different types of Do Loops and also the operators. You also learned

about Loop Until and Loop While.

Page 37: Visual Basic Tutorial

37

Visual Basic Arrays

You have seen how variables work the problem with variables is that they only hold one value. Arrays

on the other hand can hold more than one value, they are common in huge programs. Think of them like

lists say you wanted to make string variable of all your games you good use an array for that. When you

create an array it is similar as a variable but you just define the size of the elements like this:

Dim games (5) As string

The other thing is that arrays are accessed by their index number. I will show you that in a moment. Create

a new VB Console Application and name it Arrays.

Example Dim Games(5) As String

Games(0) = "GTA 4"

Games(1) = "Battlefield 3"

Games(2) = "SWAT 4"

Games(3) = "Arma 2"

Games(4) = "RollerCoaster Tycoon 3"

Games(5) = "GRID"

Console.WriteLine(Games(0))

Console.ReadLine()

When you debug this (F5) you should see it print out GTA 4. The way this works is first we make the

array and then you create that list followed by the index number. Many people forget that arrays start from

0!

User Input

This time we are going to get the input from the user.

Example Dim Games(5) As String

Games(0) = "GTA4"

Games(1) = "Battlefield 3"

Games(2) = "SWAT 4"

Games(3) = "Arma 2"

Games(4) = "RollerCoaster Tycoon 3"

Games(5) = "GRID"

Dim x As Integer

x = 0

Console.WriteLine("Pick a Number between 0 and 5")

x = Console.ReadLine()

Console.WriteLine(Games(x))

Page 38: Visual Basic Tutorial

38

Console.ReadLine()

Code Explained

This time we created a integer variable named x we gave x the value 0 (as a default value) we then asked the user to pick a number between 0 & 5 We the read that that value using Console.ReadLine and store it in x we then print it out using Console.WriteLine(Games(x))

For Each Loop

With arrays you can also loop through the array, in the next example we will print out all the values in the

array Games.

For Each GName As String In Games

Console.WriteLine(GName)

Next

Console.ReadLine()

When you run this code you should get a list of the games. This is a very simple For Each Statement. that

you learned about before.

Going Backwards

You can also loop through the array backwards to do this we use the step keyword that we learned about

before. Just like For Each statement above all we do is add Array.Reverse(Games)

Example Array.Reverse(Games)

For Each Gname As String In Games

Console.WriteLine(Gname)

Next

Console.ReadLine()

This time the array will print out but you will get it in reverse like this:

GRID RollerCoaster Tycoon 3 Arma 2 SWAT 4 Battlefield 3 GTA 4

Page 39: Visual Basic Tutorial

39

Sorting Arrays

You can also sort out arrays alphabetically. The code is pretty simple, at the top where it says Games (5)

= "GRID" below that put:

Array.Sort(Games)

Then comment out Array.Reverse(Games) in our previous For Each statement, then debug the program.

You should see this:

Arma 2 Battlefield 3 GRID RollerCoaster Tycoon 3 SWAT 4

It sorts out the array alphabetically.

Summary

This tutorial covers, the basics of Arrays. Arrays are ideal for groups of data, for example a list of your

favourite games should generally go in an array, instead of creating separate variables for each game. For

a real life example see the slideshow application.

Page 40: Visual Basic Tutorial

40

Visual Basic Methods

Methods (or procedures) are very good for reusing code and making code more understandable. A method

is just a block of code which you can call. Huge programs have methods. You will see how we can use

methods in later programs we create. You have already used methods before, like WriteLine(), some

methods allow you to pass data, as you will see later on in this tutorial.

Syntax Private Sub methodName()

End Sub

You can also use the public keyword instead of the private keyword, however, you will learn more about

Public vs Private in the classes tutorial.

Sub Main()

End Sub

Private Sub hello()

Console.WriteLine("Hello There!")

Console.ReadLine()

End Sub

If you run this (F5) you will see a black console window appear and it will close quickly. The reason for

this is we have not called the method yet. We call the method by its name which is hello we put the method

in Sub Main() like this

Sub Main()

hello()

End Sub

The program should now run and you should see it say Hello There! You can create methods using sub

as seen above or function. Sub means subroutine and does not return a value while function returns a

value.

Passing Data

You can pass data in a method (known as parameters).

Syntax Function <FunctionName)(parameter_1, parameter_2)

Page 41: Visual Basic Tutorial

41

End Function

In this example I used the Function keyword, however, you can use the Public Function or Private

Function, this controls the visibility of the method, private means it is available in the current class only,

while public means it is available to other classes as well, you will learn more about classes in the next

tutorial. If you pass any parameters into a method it will expect a return value. If you're not going to pass

any values use Private/Public Sub().

Example VAT Calculator Function VAT(ByVal pCost As Double, ByVal cRate As Double)

cRate = (cRate + 100) / 100

Return pCost * cRate

End Function

Code Explained

Create a method using the function keyword Specify the function parameters, in this case there are two pCost (Product Cost) and cRate (Current VAT

rate). The data type is double because product cost can contain decimals same with VAT rate Then cRate = cRate + 100 / 100, this gets the percentage multiplier. The cRate will be the value the user

enters for example 20. 20+100 = 120. Then 120/100 = 1.2 Then return the value, pCost multiplied by cRate

Now put this in the Sub Main(), make sure you comment out the hello method.

Console.Write("Please Enter product cost:")

Dim PC As String = Console.ReadLine()

Console.Write("Please enter current VAT rate:")

Dim cR As String = Console.ReadLine()

Dim result As Double = VAT(Convert.ToDouble(PC), Convert.ToDouble(cR))

Console.WriteLine("{0:C}", result)

Console.ReadLine()

This takes the user input and stores them in the variables PC and cR and then converts them to doubles.

VAT is the method we made and it needs arguments when you type VAT( you will see a tool-tip showing

you the data types this method accepts. You need to convert the user input (string) to double. The variables

made in a method are local and cannot be used outside of that method.

Optional Parameters

You can have optional parameters in methods, to specify a parameter as optional you use the optional

keyword, followed by parameter name, equal sign and value. Change the VAT method so it looks like

this:

Public Function VAT(ByVal pCost As Double, Optional cRate As Double = 20)

Page 42: Visual Basic Tutorial

42

cRate = (cRate + 100) / 100

Return pCost * cRate

End Function

As you can see cRate is now optional and has default value of 20, all optional values have to go at the end.

In the Sub Main change the code so it looks like this:

Console.Write("Please Enter product cost:")

Dim PC As String = Console.ReadLine()

' Console.Write("Please enter current VAT rate:")

' Dim cR As String = Console.ReadLine()

Dim result As Double = VAT(Convert.ToDouble(PC))

Console.WriteLine("{0:C}", result)

Console.ReadLine()

This time you do not need to specify the second parameter. As it has a default value of 20.

Overloading Methods

Overloading methods can be extremely useful, for example you might want to perform multiple functions

on the same method but just change the parameters. To specify a method is overloaded you create multiple

methods with the same name but different parameters like this:

Public Function Games(ByVal newGames As String())

End Function

Public Function Games(ByVal newGames As String)

End Function

The parameters must be different this would not work:

Public Function Games(ByVal newGames As String)

End Function

Public Function Games(ByVal newGames As String)

End Function

VB would not know which method to work with. Also something like this also would not work:

Public Function VAT(ByVal pCost As Double)

End Function

Public Function VAT(ByVal pCost As Integer)

Page 43: Visual Basic Tutorial

43

End Function

Although the data types are different the user can still put something like VAT(20) now which method

should VB work with? Doubles can contain integer values.

Example – Overloaded Method Public Function Games(ByVal newGames As String())

For Each g In newGames

Console.WriteLine(g)

Next

Return Nothing

End Function

Method 2 Public Function Games(ByVal newGames As String)

Console.WriteLine(newGames)

Return Nothing

End Function

These two methods are different one accepts an array of values and one simply accepts a single value.

In Sub Main put this;

Dim myGames As String() = {"GTA 5", "BF4", "GRID2"}

Console.WriteLine(Games(myGames))

Console.ReadLine()

Or a single value

Console.WriteLine(Games(“GRID 2”))

Console.ReadLine()

When you start typing VS will show a tool-tip telling you want arguments the method accepts.

Page 44: Visual Basic Tutorial

44

Description

If you noticed when you use the Console.WriteLine() method it gives a small description of the method

and the parameters, you can easily add that to your own methods, to add it simply put 3 apostrophe’s

above the method, VS will automatically insert the syntax then.

Example ''' <summary>

''' Prints out a single list of games

''' </summary>

''' <param name="newGames">String Games, What game do you like?</param>

''' <returns></returns>

''' <remarks></remarks>

Public Function Games(ByVal newGames As String)

Console.WriteLine(newGames)

Return Nothing

End Function

When you call the method now, VS will automatically provide the description. (A tooltip)

Summary

Sub means subroutine Sub does not return a value, function does When giving information to methods it is known as parameters Variables in methods are local You call a method by its name

Page 45: Visual Basic Tutorial

45

Visual Basic Managing Errors

In every computer program released there is always a problem (known as a "bug") the thing is these can

occur at any time. We can solve these easily by using a try catch block to "catch" the exception. There are

different types of exceptions which can occur it can be an overflowException or a formatException. Create

a new VB Console Application and name it ManagingErrors. Copy the following:

Dim x As String = Nothing

Dim a As Integer = 10

Console.WriteLine("Pick a number")

x = Console.ReadLine()

Console.WriteLine(Convert.ToInt32(x) + a)

Console.ReadLine()

This is a simple program that we have seen in other tutorials, we got two variables one a string and another

a integer, we tell the user to pick a number then add both values together, we use Convert.ToInt32 to

convert the string data to integer. Go ahead and run the program type in 20 you will get the answer 30.

OK this works without any kind of problems but what happens if you type the letter K? Well if you go

ahead and try it the program will crash and you will get an error saying "Input string was not in a correct

format" something which looks like this:

This is a format exception as you can see by the title, now we can put this code in Try Catch block and

prevent the crashing.

Syntax Try

Catch ex As Exception

End Try

Page 46: Visual Basic Tutorial

46

Example Try

Console.WriteLine("Pick a number")

x = Console.ReadLine()

Console.WriteLine(Convert.ToInt32(x) + a)

Catch fEx As FormatException

Console.WriteLine(fEx.Message)

End Try

Console.ReadLine()

Now fEx is a local variable, and the code executes as normal however if the user types in a letter or non-

integer then the Format Exception error message will appear. The code has simply been moved to the Try

Catch block. Now this works perfectly try running it, the error message will appear in the console window

and the program won’t crash. However, there are many exceptions which can happen another type of

exception is Overflow exception where the number goes out of range for example Integer has a range

between -2,147,483,648 to 2,147,483,648 which is a pretty big number however if the program goes over

this, the catch handler will not catch it. Run the program again and this time for your number type

214748364833 the program will crash with the error "Value was either too large or too small for an

Int32" stop the program and return to the IDE.

Nested Catch Handlers

We can have nested catch handlers for different types of Exceptions just below that

Console.WriteLine(fEx.Message) put this code:

Catch oEx As OverflowException

Console.WriteLine(oEx.Message)

Now when you run the program and type 214748364833 the message will appear in the console window

instead of crashing the program. Now there are many more exceptions which can occur we can't go through

all of them but I showed you two common ones. Now the thing is how would you catch any exception?

In this case you just use the keyword Exception. Let’s modify our code a little, where it says:

Console.WriteLine(Convert.ToInt32(x) + a)

Change it so it looks like this:

Console.WriteLine(x + a)

Run the program and type a number (from 1 to 10) the program should calculate as usual. However go

ahead and type in a letter and watch how the program will crash with the message "Conversion from

Page 47: Visual Basic Tutorial

47

string "f" to type 'Double' is not valid." (f is the letter I picked) none of the catch handlers handled the

exception this is because the exception was a "InvalidCastException" there are many more exceptions

now to catch this exception below the overflowException add another catch handler like this:

Catch ex As Exception

Console.WriteLine(ex.Message)

This will catch all exceptions.

Summary

In this tutorial you learned how to manage errors this will ensure your programs are robust. However, this

does not mean write try catch statements everywhere in your code, do it where problems are likely to go

wrong for example if you had an email program many things can go wrong with sending email for example

the email is not in correct format, the password is not correct, the server is down etc.

Page 48: Visual Basic Tutorial

48

Visual Basic Creating and Managing Classes

In the previous tutorials you worked with classes, Console is a system class and WriteLine is one of its

methods. You can make your own classes which become useful for code reuse. Classes simply contain

methods or events. In the example below we will create a simple application which calculates VAT there

will be three calculations it will be able to perform.

Syntax Public Class <classname>

Your methods here.

End Class

Create a new Visual Basic Console Application name it Classes. In solution explorer right click classes

and make a new class file name it Car.vb (See image below).

Next we are going to create some methods, copy the code below.

Public Function manufacturer(vmanufacturer As String)

Return vmanufacturer

End Function

Public Function model(vModel As String)

Return vModel

End Function

Public Function colour(vcolour As String)

Return vcolour

End Function

Here we have made a few methods and are simply returning the parameter. Now in the Module.vb file

add this;

Dim myCar As New Car()

Console.WriteLine("Please enter your car manufacturer: ")

Dim m As String = myCar.manufacturer(Console.ReadLine())

Console.WriteLine("Please enter car model :")

Page 49: Visual Basic Tutorial

49

Dim mo As String = myCar.model(Console.ReadLine())

Console.WriteLine("Please enter car colour")

Dim c As String = myCar.colour(Console.ReadLine())

Console.WriteLine("You car details: " & vbLf & " " & m & " " & vbLf & " " & mo & vbLf

& " " & c)

Console.ReadLine()

This is a very simple class, we first create the variable myCar and then initialize it. Then we print to the

console and read the users results just like we have done in previous tutorials. We finally print out the

details the user entered. When you type myCar. you will get a list of methods this class has.

Public vs Private In the above example I use public function, now public allows this method to be accessed inside of the current

class and on the outside of the class (so it can be accessed by another class). If I was to change this to private

function then the method is not accessible from the outside only from the inside of the current class.

VAT Application (Calculator)

The above example is very simple and has very little code, in the next example we will make a VAT

application it will perform 3 tasks which are;

Calculate total product cost including VAT Calculate the VAT you're going to pay Calculate the amount of VAT you paid when the product already has VAT added.

Comment out the previous code you have written then make a new class file and name it VAT.vb. We

will write three (3) methods follow along;

Method 1 Public Function totalProductCost(ByVal pCost As Double, ByVal cRate As Double)

Dim CR As Double = (cRate + 100) / 100

Return pCost * CR

End Function

This method calculates the total product cost when you add VAT. To calculate the VAT we use the

percentage multiplier so the current VAT rate is 20%;

1. 100 + 20 = 120 2. 120 / 100 = 1.2 3. <product cost> * 1.2 = answer

Page 50: Visual Basic Tutorial

50

We have a variable called CR this calculates the percentage multiplier and we then return pCost * CR.

(ProductCost * CurrentRate). We also have two parameters pCost and cRate, this will be used to make

the calculation when we ask the user for the product cost and VAT rate.

Method 2

This time we will calculate the VAT amount which is being paid.

Public Function CalculateVAT(ByVal productCost As Double, ByVal currentRate As Double)

Dim CR As Double = (currentRate + 100) / 100

Dim totalCost = productCost * CR

Return totalCost - productCost

End Function

This method is similar to the above one however the difference is that we return the totalCost (VAT has

been added) subtracted by productCost (Original amount ex VAT). This gets the VAT amount we paid.

Method 3 Public Function origPrice(ByVal itemCost As Double, ByVal vatRate As Double)

Dim cRate = (vatRate + 100) / 100

Dim oPrice = itemCost / cRate

Return itemCost - oPrice

End Function

The last method gets the VAT amount you paid, when VAT is already included in the price. We first get

the percentage multiplier, then we divide the product cost by the percentage multiplier. Then we simply

subtract itemcost by original price.

Now that we have written the methods it is time to call them, return to Module.vb and below the Sub Main

method add this;

Sub VATApp()

End Sub

Now inside this method we will write our code we will use an if statement to determine the function the

user has picked there are 3 functions in our application. Copy this;

Dim f As String = Nothing

Dim myVAT As New VAT

Console.WriteLine("PRESS C TO CALCULATE TOTAL PRODUCT COST INC VAT, PRESS R TO

CALCULATE VAT AMOUNT PAID, PRESS A TO CALCULATE ORIGINAL PRICE")

f = Console.ReadLine()

Page 51: Visual Basic Tutorial

51

Here we have a variable called f which is nothing we then initialize our variable myVAT and create a new

object. When you use the new keyword you are creating an object. We then print to the console and read

the line. Now here is the first part of the if statement;

1:

Now the first function will calculate the total product cost including VAT

If (f = "c") Then

Console.WriteLine("Please Enter Product Cost (EX VAT): ")

Dim pCost As String = Console.ReadLine()

Console.WriteLine("Enter Current VAT Rate: ")

Dim CRate As String = Console.ReadLine()

Dim result As Double = myVAT.totalProductCost(Convert.ToDouble(pCost),

Convert.ToDouble(CRate))

Console.WriteLine("The total cost is: {0:C} ", result)

This is similar to our previous tutorials we first get the user input and read the value. Then we have a

variable called result which is data type double. Here you can see we call our class myVAT. When you

type myVAT. you will get a list of methods available to the class, and when you insert the brackets you

will get a tool-tip showing you the arguments this method takes. The method cannot take 0 arguments! In

the arguments we convert the strings to double. Then we print out the result the {0:C} gives the result the

currency symbol.

2:

Now below that if statement and the second part, this calculates the VAT amount you are going to pay.

ElseIf (f = "r") Then

Console.WriteLine("Please Enter Product Cost (EX VAT): ")

Dim productCost As String = Console.ReadLine()

Console.WriteLine("Please Enter VAT Rate: ")

Dim CurrentRate As String = Console.ReadLine()

Dim VATPaid As Double = myVAT.CalculateVAT(Convert.ToDouble(productCost),

Convert.ToDouble(CurrentRate))

Console.WriteLine("VAT being paid: {0:C} ", VATPaid)

Console.WriteLine("Total cost is: {0:C} ", Convert.ToDouble(productCost) +

Convert.ToDouble(VATPaid))

This is similar to the above method it performs the exact calculation however it gets the VAT amount

being paid, also the last line gets the total cost.

Page 52: Visual Basic Tutorial

52

3:

Nearly done! The last method will get the VAT amount paid when VAT is already included.

Else

If (f = "a") Then

Console.WriteLine("Please Enter Product Cost (INC VAT): ")

Dim totalCost As String = Console.ReadLine()

Console.WriteLine("Please Enter VAT Rate: ")

Dim vatR = Console.ReadLine()

Dim total As Double = myVAT.origPrice(Convert.ToDouble(totalCost),

Convert.ToDouble(vatR))

Console.WriteLine("VAT Added: {0:C} ", total)

Console.WriteLine("Original Price: {0:C} ", Convert.ToDouble(totalCost) -

Convert.ToDouble(total))

End If

End If

Console.ReadLine()

This will get the VAT amount we paid and also the original cost. Now this program will not run yet so in

Sub Main you need to put this;

Dim x As Integer = 3

While x = 3

Try

VATApp()

Catch ex As Exception

Console.WriteLine(ex.Message.ToString())

End Try

End While

Console.ReadLine()

This is a simple while statement it calls our method VATApp the reason it is in a while statement is

because it will keep looping so once you finish your calculation you can do another one.

Summary

Class start with the class keyword A private method is available inside the current class and public one is available both inside and outside When you use the new keyword you are making a new object Remember to initialize class variable

Page 53: Visual Basic Tutorial

53

Visual Basic Text Editor

A new text editor tutorial is available at the blog!

In this tutorial you will build a text editor, this will be a simple text editor something similar to Microsoft

WordPad. Before you begin make sure you have covered the Visual Basic tutorials, this tutorial uses basic

VB knowledge mostly, if statements, for and foreach statements, and methods. Since the tutorial is long

it is available as a PDF only. Download it from below.

Text Editor Contents ABOUT

LICENSE

PART A – DESIGN PAGE 2

SAVE WORK – DIALOG

OPEN WORK –DIALOG

THE MAIN MENU

THE TOOL BAR

THE STATUS STRIP

THE CONTEXT MENU STRIP

THE RICHTEXTBOX

THE TIMER

PART B – CODING PAGE 11

CREATING REGIONS

MAIN MENU - FILE

MAIN MENU – EDIT

MAIN MENU – TOOLS

TOOL BAR

TOOL BAR – BOLD, ITALIC, UNDERLINE, STRIKETHROUGH

TOOL BAR – ALIGN LEFT, RIGHT, CENTER, WORD CASE, AND ZOOM

TOOL BAR – FONT SIZE AND FONT-FAMILY

RIGHT CLICK MENU

YOU’RE DONE