Professional Documents
Culture Documents
Contents
S. No Topic Page No
1
Introduction to Visual Basic 2015
Visual Basic 2015 is a part of Visual Studio Community 2015. Visual Studio Community 2015 comes with
many new and impressive features to support cross-platform mobile development, web & cloud development,
IDE productivity and more. Here, we will be focusing on creating desktop applications using Visual Basic.
Visual Basic (VB) is an event based programming language and Integrated Development Environment
(IDE) from Microsoft. VB has been derived from BASIC. Visual Basic 2015 is an Object-Oriented
Programming (OOP) Language and is bundled together with other Microsoft Programming languages C#, C++ ,
JavaScript, Python and more in a package called Visual Studio Community 2015.
1. Once installation is complete, run Visual Studio 2015 application. The first page you will see will look like
this:
2. Click on New Project. This will open another page like the one shown here.
2
3. Make sure that Visual Basic is selected under the Templates. Select Windows Form Application
right at the top, which will help us in building desktop applications. The default location of Visual
Studio Folder appears in the Location.
4. Change the default name to My_First_project and click on OK. This opens the Visual Basic 2015
IDE. An IDE provides user interface tools for building, testing and refining a platform and its
features. In simpler terms, an IDE consists of an editor, compiler and debugger.
3
Title Bar
Visual Basic 2015 IDE:
Menu Bar
Standard Toolbar
Tool Box
Properties Window
Error List
This window is also known as the design window in VB. Let us now understand the functions of these
screen components.
A Form is the object where the actual GUI will be designed by arranging the components visually.
The ToolBox is situated on the left hand side and contains various components that can be used on the
Form. Tools are also known as Controls that perform various tasks. Ex: Button, ListBox, PictureBox and so
on.
The Solution Explorer is a pane that shows an organised view of projects, files and gives ready access to
these files.
The Properties Window shows the properties of the chosen tool or control. These properties can be edited
by the designer.
Before we start our designing our first project in VB, we need to learn some basic terms about event based
programming languages.
4
Event-driven: Programs that operate in a GUI are always event driven. This means that nothing occurs
until the user does something like clicking a button or entering text and so on.
Design Window: The design window is the place where we create how our GUI will appear to the user.
This acts as the front end of our program.
Code Window: Here, we need to give some code so that when the user takes an action like clicking on a
button in the GUI, then a result will be seen. The code given here is the back end of the program.
First VB Program:
1. In the Design window that has been opened, drag a button (or you can double click on the button)
from the toolbox and place in on the form.
2. On the Properties Window, find the Text property of the button and change the Text to Click Here!
And press enter.
3. Double click on the button that has been inserted into the form. This will open the source code
window, displayed as Form1.VB.
4. Insert the following code below the Private Sub Button1_Click... command:
When this code is inserted in the Button1.Click event, the message pops up when the button is clicked by
the user during run time.
5. Now run the program by clicking on the green triangle with text Start on the Standard ToolBar.
5
When the Start tab is clicked, VB loads and compiles the project into a collection of modules, data and
other information, prepares program for testing or debugging and then runs the program in the
development environment.
6. A new Form opens with the button. Click on it. The message that we had included in the source
code will be displayed.
12. Click on the OK button to close the message box. To close the application, we can close the Form1
window or we can click on the Stop Debugging button (A brown square) on the Standard Toolbar. In order
to edit our code, we need to stop debugging first.
13. To save your program, click on the Save All icon in the Standard Toolbar. This saves the Design
window and the code window.
We can add images by loading an image onto the Form using a PictureBox during design time. Create a
New Project in VB. The application you are going to create will have a button and a PictureBox. When the
button is clicked, an image should be displayed.
To add a picturebox to the GUI you are designing follow these steps:
6
5. Click on the Visible Property of the PictureBox and Choose False. That means the picture will not
be displayed initially.
6. Click on the Image property. Click on the ellipses at the end. A dialog box opens. Click on Local
resource file and click on Import. Choose the location of your image and double click on it to load it.
7. Drag a button onto the form and change the text property to “Surprise!”
8. Double click on the button to enter the source code, Form1.VB window.
9. Add the following line of code under Private Sub Button1_Click....
During run time, when the user clicks on the button that says “Surprise!”, the picture that is not visible till
then becomes visible. The user takes an action by clicking on the button and the result is the image is
seen. Imagine if we have more than one button on our GUI. How does VB know which button should start
what event? Every time we drag and drop a control, a default name is given to it by VB. The first button we
add will be known as Button1, the second as Button2 and so on. The name of a control can be seen on the
Name property of a control. In the same manner, since we have dragged only one picture box, it has a
default name of PictureBox1. We can always modify the name property of a control.
7
When the visible property of the PictureBox is set to true under Button1, during run time when the button is
clicked, the picturebox and hence the image loaded in the picturebox becomes visible.
10. Click on the Run tab. A new form with only the button opens.
11. Click on the button. The image will be seen.
We know that controls are nothing but tools that we can use in building a GUI in Visual Studio. These
controls are present in the Toolbox and can be dropped on the Form to be used. Other than the PictureBox
and Button which have been used, there are useful controls which we may require when designing our
GUI. These include:
1. Label - This is used to display text that can be modified by the program but not by the user.
2. TextBox – This is used to accept text input from the user.
3. Radiobutton – The name is based on the functionality of old radio buttons which were pushed down
to select. If one was pushed down, the others came up to show their unselected state. When a user
has to choose one option out of many, a radiobutton is used.
4. GroupBox – This control allows the user to create a frame on the form. Any controls placed within
the groupbox can be moved as a unit. This control is normally used with the radiobuttons.
5. CheckBox - The CheckBox control allows the user to set true/false or yes/no type options. The user
can select or deselect it. When a check box is selected it has the value True, and when it is cleared,
it holds the value False.
6. ListBox - The ListBox allows the user to display a list of items and add items during runtime to the
listbox.
8
Answer these questions:
8. What is the use of checkboxes in GUI? How are they different from radiobuttons?
9. Give any two events that can happen for a button.
9
VARIABLES, DATA TYPES AND OPERATORS IN VB 2015
A variable is a temporary storage location for your data in the program that you have designed. WE can
use any number of variables in our program. But before we use variables in our program, we need to set
aside some memory space for the variable. In other words, we are reserving space for the variable. This is
known as variable declaration.
But how do we know how much space needs to be set aside? That depends on the type of data that will be
stored by the variable. VB wants to know the name and the type of variable in advance so that the compiler
can set aside the memory the program will need to store and process the information held in the variables.
Different data types have different space requirements and size limitations.
DATA TYPES in VB
There are many data types such as Short, UShort (unsigned short), Integer, Long, Decimal, Double, String,
Boolean and so on. We will learn about a few of these only.
Integer data type stores only integers, both positive and negative. Ex: -2, 3, 0
Double data type stores numbers that have decimal fractions in them. Ex: 3.145, -5.678
String data type holds any text or alphanumeric data. They are enclosed in double quotes. Ex: “Mansi
Gupta”, “abc1234$”.
In the above line, Dim and As are known as keywords. They are words that have a special meaning to the
compiler. We cannot use a keyword to name our variable. Dim stands for Dimension. So, if you have a
variable name known as stu_name and since you are going to be storing text data in this variable, you
would use the Dim statement as follows:
As another example, if we want to create a variable called score which holds the score of a user in a game,
we will initialize it as Dim score As Integer.
Operators in VB
Operators are symbols that perform a specific operation on operands. Operands are variables or constants.
For example, in the statement a + 7, the plus sign is an operator, a is a variable and 7 is a constant. Using
operators and operands, we can create expressions and formulas. An expression consists of a legal
combination of operators and operands. What does legal mean? If we say a + * 7, then it is not legal as two
operators are placed one after the other. A formula is an assignment of a combination of numbers,
operators, keywords to a new variable. Ex: b = a + 7.
10
There are three main types of operators in VB:
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
\ Integer Division -
Mod Remainder-division
^ Raised to the power of
& String concatenation
The first four operators are the basic arithmetic operators. The integer division operator is used
to return only the integer value of the quotient after division. Ex: 9/4 gives 2.25. 9\4 gives 2.
The Mod operator gives the remainder of a division. Ex: 9 Mod 4 gives 1. The exponentiation
operator raises one number to the power of another. Ex: 2 ^ 4 gives 16. The string
concatenation operator is used to join two texts together. Ex: “oranges and” & “apples” give
“oranges and apples”.
Operator Description
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
<> Not equal to
= Equal to
These operators are used to check if a given condition is true. They return only true or false as
answers. In VB, the equal to sign is used both for assignment as well as for checking equality of
an expression. If a = 5 and b = 3, then
a <> b returns True
a <= b returns False
Operator Description
and Returns true if both operands are true
or Returns true if any one of the operands is true
not Used to reverse the logical state of an operand
11
Calculator GUI in VB: To create a GUI that lets the user insert two numbers and choose an
operation from four radiobuttons. The answer should be displayed in a label.
Design:
Code:
12
Understanding the code:
The text property of any control is related to the text it displays and is of String data type. The Dim
statements are used for declaring the two numbers which will be used in the calculations. In this example,
the answer is also stored in a variable z. Since we need to perform arithmetic operations on the numbers
entered by the user, they cannot be of String data type. They need to be a number data type, i.e, Double or
Integer. The Val() function extracts the numeric value of the string. So, Val(“56”) is 56 and Val(“-4”) is -4
and so on.
When a radiobutton is selected, the operation corresponding to that is carried out and the answer is
assigned to z which in turn is assigned as the text of a label.
Output:
Modify the above GUI to include Integer division and exponentiation operator in your calculator.
13
Introduction to Control Structures in VB 2015
Start
Sum = a + b
Print sum
End
A GUI that displays answers after accepting 2 numbers and calculating the sum, difference, product
and quotient of these numbers is an example of sequential control structure.
Code:
14
Output:
Decision construct: Here, the flow of control is not in order. Depending on whether a condition is met, that
branch of program is executed. In the given example, if a > b, a is printed. If this condition is not met, b is
printed.
Example: Flowchart that accepts two numbers and prints the larger number.
Start
N
Is a >
Print b
b?
Print a Stop
15
If Statements in VB 2015
We can test a condition in a programming language by using a special block of statements known as the If
statements. In the simplest form, an If-Then statement can be used to execute a set of statements in the
event that a condition is true.
If <condition> Then
<statements>
End If
Consider this example where a label displays positive or negative based on the input given by user in a
textbox.
Label1.Text = “Positive!”
End If
What happens if the textbox contains -3? The above block of code will not cause anything to be displayed.
By using Else, we can execute some statements when the condition is not true or false.
If <condition> Then
<Statements>
Else
<Statements>
End If
For the same example as given above, our code will change as follows:
Label1.Text = “Positive!”
Else
Label1.Text = “Negative!”
End If
However, these blocks of code will not give any output for one specific input value. What value is that?
16
Example of If-Else statement:
Create a GUI in which there is a textbox for the user to enter a password and a button. When the button is
clicked, an appropriate message should be displayed on a messagebox depending on whether the correct
password has been entered.
Design:
Code:
We create a String variable pw that will store the correct password. This needs to be a string variable as
passwords are normally alphanumeric. When the button is clicked, we assign the correct password to the
variable pw. Then if the password matches the one given by the user in the textbox, the messagebox
displays „Login Successful!‟ otherwise it displays „Login failed!‟.
Output:
If <condition> Then
17
<statements>
ElseIf<condition>Then
<statements>
Else
<statements>
End If
Whenever we have more than one condition to be tested, we use If-ElseIf-Else. We can have as many
ElseIf statements as needed in a concatenated (If-ElseIf) statement.
Example:
Create a GUI that accepts a number and checks if it is positive, negative or zero.
Design:
Code:
18
Output:
We can create random numbers (numbers that cannot be predicted beforehand. These numbers do not
follow an order or sequence.) in VB using the Rnd() function.
The Rnd() function creates a random number in the range: 0<=x<1. In order to create integers in the range
1 <= x<=6, we modify the Rnd() function in this manner:
x = Int(Rnd()*6 + 1)
Y = Int(Rnd()*10)
Create a GUI with a button, picturebox and a label. When the button is clicked, the picturebox should
display one of the faces of the die.
19
Code:
We create a variable x which stores a random number. In this example, when button1 is clicked, a random
integer in the range 1 <= x <= 6 is created. Why do we need this range? A dice has normally six faces,
each face displaying a number 1 to 6. Hence, to create a virtual dice, we need to randomly dislplay any
number from 1 to 6. Depending on the value of x, a picture is displayed in the picturebox. The function
Randomize() ensures that the same set of random numbers are not repeated every time we run the
application.
Output:
20
Select Case in VB 2015
Select Case control structures can be used in place of If-ElseIf-Else structures. The Select Case is more
efficient when the branch of the program to be executed depends on specific test cases.
Age Message
6 to 10 Geronimo Stilton
11 to 15 Harry Potter
Any other age Invalid age! Please enter age in the range 1 to 100
Design:
21
A label is used to give instruction to the user. A textbox is used to accept age from user. A button is used to
display message on label2.
Set the text property of label1 as given in the GUI.
Set the text property of label2 to null.
Set the text property of the button to Get Message!.
Code:
Expected Output
22
Loop Control Structure
Loop Control or Repetitive Structure: In this type of control structure, a set of statements are repeatedly
executed if the test variable meets a condition. A loop structure can be entry controlled or exit controlled. In
an entry controlled loop, the condition is tested at the beginning of the loop. In an exit controlled loop, the
condition is tested at the end of the loop.
Example of a Loop Control: Flowchart to print the first ten natural numbers. In this example, condition is
tested after the execution of the loop statements. Hence this flowchart shows the structure of an exit
controlled loop.
23
Loops in VB 2015
We will be learning about three types of loop structures in VB: For - Next loop structure, the Do-While-Loop
structure and the Do-Loop-While Structure. The Do-Loop-While structure is an exit control structure and the
other two are entry controlled.
For loop Syntax:
For <var> = <start> To <end> Step <step size>
<statements>
Next <var>
The words in blue are part of the syntax and cannot be changed. start, end and step size are numeric
values. The variable starts with the initial value given as start and for each of these values, the statements
within the loop are executed. Each time the loop runs, one iteration gets completed.
GUI to print the first ten natural numbers in VB: The GUI has a button and a label. When the button is
clicked, the numbers should be seen in the label.
1. Drag and drop a label and a button.
2. Change the text of the button to Generate numbers! and change the autosize property of the label
to False.
3. Increase the size of the label so that it can fit the first ten numbers and leave the text property
empty.
4. Double click on the code and write the For loop statements under the button.
6. Now run the program. The output seen in the label should be like this:
24
Understanding the code:
When the button is clicked, the variable i starts with the value 1. The value of i is checked against the
condition i = 1 to 10. What this means is, if the value of i is greater than 10 or less than 1, the loop
statements will not be executed and control passes to the statement after the loop (after Next). If it is within
the given range, the loop statements are executed. Hence For loops are entry controlled loops.
Since for i = 1, the condition is satisfied, the loop statement Label1.Text = Label1.Text & i & vbCrLf
is executed.
The ampersand operator (&) is used to join two text values together. In this example, the previous value of i
present in the Label1 should be displayed along with the new value of i. So, when i = 2, both 1 and 2 needs
to be seen. Label1.Text (new) is modified as Label1.Text (old) which is 1 & new value of i which is 2. This
way, both 1 and 2 are displayed. When i becomes 3, 1, 2 become the old values and the new value of i, 3
is added to the label. But we need to make sure that the new value is displayed on a new line and not on
the same line. For this purpose, we have the vbCrLf character which stands for visual basic Carriage
Return Line Feed. Carriage Return causes the cursor to come back to the beginning of the same line. Line
Feed causes the cursor to move to the next line. By using vbCrLf, we are moving the cursor to the
beginning of the next line to print the new value of i.
25
Double click on the button and insert the given For loop statements under the Button1_Click event.
For i = 99 To 1 Step -2
TextBox1.Text = TextBox1.Text & i & vbCrLf
Next
Understanding the code
Since we need to print the numbers in descending order, we need to start with the upper limit and move to
the lower limit of the range. Even though the upper limit has been given as 100, we start from the initial
value of 99 instead because odd numbers can be generated by starting with an odd number and doing skip
counting of two from that number. The step size is negative as we are moving from the upper limit to the
lower limit. If we give a positive step size of 2, then the next i becomes 101 which is outside the range of i
allowed.
Expected Output
We can use the vertical scroll bar to see all the odd numbers in the range. This is an advantage over using
a label. In a label, the size of the label needs to be fixed during design time to be large enough to display all
the numbers.
What happens if we click on the button again? The odd numbers in the range 99 to 1 are printed again!
This is because we have not cleared the TextBox before the For loop started. To clear the TextBox such
that it holds no text every time the button is clicked, insert this line of code before the For loop is started.
TextBox1.Text = “”
By setting the text property to null, we are clearing the text box of its contents.
Design:
26
Code:
Expected Output:
27
Do-While-Loop in VB
Do-While-Loop Example
GUI to print even numbers from 155 to 240:
The design of the GUI is the same as last example. We can add a label informing the user that even
numbers will be generated.
Double Click the button to insert this code under the Button1_Click event:
In Do-While, we are using a variable which should have an initial value outside the Do loop. First declare
the variable under Public Class Form as follows:
Dim z As Integer
The first value of z should be 156 and not 155 as we require only even numbers.
Initialize z under before the loop statements like this:
z = 156
Code:
28
Expected Output:
Do-Loop-While Structure
The Do-Loop-While structure is an exit controlled loop structure where the condition is tested at the end of
the loop.
Syntax:
Do
<statements>
Loop While <condition>
Do-Loop-While Example
29
Code for the GUI:
The value entered in the Text Box is assigned to the variable n. We need another variable count which will
keep track of the number of multiples being generated. We will be displaying ten multiples. Hence the
condition checked is count <= 10.
We use the ListBox1.Items.Add() method to add values given within the brackets to the list box. Here,
vbCrLf is not needed as each item is added on a new line in the box.
In order to clear the list box of previously held values, we use ListBox1.Items.Clear().
The statement End in button2 closes the running GUI. We can also use Me.Close() instead of End. In VB,
the form that is open is addressed as Me.
In order to print the output in the form n x 1 = n, we have used this line of code:
ListBox1.Items.Add(n & " x " & count & " = " & n * count)
The text enclosed within parenthesis is printed as such without any modification. count value keeps getting
incremented in every iteration. n value remains a constant. n*count changes depending on count value.
These are variables or expressions that cannot be enclosed within double quotes.
30
Expected Output
What happens if we start with initial value of count as 11? When count is initially 11, it does not pass
the condition count <= 10. However, the condition is only tested after the multiple is displayed. So, we will
see 5 x 11 = 55 in the listbox. At the end of the loop, count value does not pass the condition and flow of
execution exits the loop.
Output when count = 11 initially and n = 5:
Create a Lucky Seven game of luck. The user should click on a button to generate three random
numbers. If the numbers are all 3, give a congratulations message and display a pot of gold.
Otherwise, give a “Keep trying” message.
Modify this GUI further such that if all three random numbers are the same, then the pot of gold is
displayed.
31
Answer these questions:
32
Database Connectivity in VB 2015
Visual Basic 2015 can be used to work with databases, typically to display, modify, search database
content. Visual Basic provides suitable front end such that the user is presented with a helpful window to
manipulate the database.
In this section, we will learn how to connect to a database in MS Access and modify the table through VB.
2. Open Visual Studio 2015 and create a new project titled Employee_Form.
4. The data source wizard opens. Click on Database and then on Next.
6. Click on New Connection; make sure that the Data Source is a Microsoft Access Database File and
click on Browse to choose where your Access file is located.
33
7. Once you have located the file, click on Test connection to check if VB has established a connection
with the Access database. The data source wizard attempts to open the database with the
connection string that has been created. If it works, you will see a message similar to the one shown
below.
8. When you click on Next, you will get a prompt that asks you if you want a copy of your File. Click on
No and then on Next.
34
9. The next window asks you to choose the required Database objects. Click on Tables, Then
Emp_Table and choose all the fields under the table. Click on Finish to create the new data source.
Your Solution Explorer should now include the new XML schema that is the dataset that you have
created from the Access file.
11. Right click on abc_Employee_detailsDataSet.xsd in the Solution Explorer and then click the View
Designer tab in the drop down menu.
12. We see the Dataset Designer that shows the field names and the table name of the database. The
Dataset Designer contains tools for creating components that communicate between your database
and the application. We can create and modify table adapters, queries, data tables, fields and
relationships with this Designer. We can also set properties related to the objects of the dataset.
13. Click on Last_Name field. In the Properties window, click on the MaxLength property and change
the default value of 255 to 50.
35
The Data Sources Window
The data source window is used to display a visual representation of the datasets connected to the Project
and also, it helps bind these datasets to the controls on the Form. To view the Data Sources Window, Click
on View -> Other Windows and then on Data Sources. Sometimes, the Data Sources tab is visible on the
left hand side of the Form. Make sure you close the Database Designer window that you opened earlier.
Your Data Sources Window should look like this:
1. Click on the Last_Name Field in the Data Sources Window. A drop down arrow appears next to it.
Clicking this arrow displays control options that can be used with this field.
2. Click on TextBox and drag the Last_Name field to the middle of the form in the Windows Form
Designer.
36
3. Now run the program to see how the database is connected to application.
On running, we see that the textbox contains the first Last_Name of the database.
We can move through all the records of the database by using the navigation pane on top.
4. Delete the last record of the database by using the delete tab in the pane. We see that the
Navigation pane indicates 9 records now instead of 10.
37
What happens when we close the application and run it again? We will see ten records instead of nine.
This is because our data source has ten and when we deleted one record in the data set, it does not modify
the original data.
We can view the entire table by dragging and dropping the table from the Data Source to the Form
Designer. This is called the Table Grid View.
We can add new records by clicking on the + sign in the Navigation Pane. The default ID for a new record
is -1. Change it to whatever Id you require.
After the new Record is entered in the Text Box, click on Save tab. The new record gets added to the
existing table.
38
Menustrip in VB 2015
Steps to insert a menutrip:
3. At the field that says Type Here, we can type what menu options are needed for our application.
Type Exit in the box.
4. Now, we have a tab on our application that says Exit. But in order for it to work, we need to give the
code in the Form1.vb window. Double click on Exit to go to the code window.
5. Type Me.Close() under ExitToolStripMenuItem event.
It is possible to create shortcuts to menu options using the ampersand (&) symbol before the shortcut
alphabet. For example, in the above example, if we want to create a shortcut for Exit as alt + x, then in the
menustrip control, type E&xit. This causes an underline to appear under the letter x.
39
When the application is run, pressing the alt key and x key closes the Form.
1. Add another menu option Help along with Exit and add a sub menu for Help that says About. By
placing the ampersand sign before A, we can create a shortcut for the About menu.
2. Type the code for the About menu in the code window. Add a few lines in a message box which will
be displayed when this menu option is chosen.
3. Now run the application again. When About option is chosen, the message box displays the given
message.
40