You are on page 1of 40

Visual Basic 2015

Contents

S. No Topic Page No

1 Introduction to Visual Basic 2015 2


2 Variables, Data Types and Operators in VB 10

3 Control Structures in VB – Sequential and Decision 14


4 If statements in VB 16
5 Select Case in VB 21

6 Control Structures in VB- Loops 23


7 For loops in VB 24
8 Do While loops in VB 28

9 Database Connectivity with MS Access 33


10 Menustrip in VB 39

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.

To install Visual Studio Community 2015, follow these steps:

1. Go to the link https://www.visualstudio.com/downloads/download-visual-studio-vs


2. Click on Download Community Free. Download will start automatically.
3. Once the exe file is downloaded, click to run it.
4. Select Custom Option and click on the Next button.
5. Uncheck all options as these are add on features apart from VB 2015 and click on Install.

Visual Studio Community 2015 Start Page

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

Form Solution Explorer

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.

The Error List identifies the errors in the program.

Before we start our designing our first project in VB, we need to learn some basic terms about event based
programming languages.

GUI: Acronym for Graphic User Interface.

Event: An action that a user takes, like clicking on a button.

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.

Adding images onto a Form

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:

1. Name your project, Image_load_design and click on Create.


2. Locate PictureBox in the ToolBox and drag it onto the form.
3. Change the size to your liking by dragging the handles on the edges of the PictureBox.
4. Make sure the PictureBox is selected and on the Properties Window, click on SizeMode and choose
StretchImage. This will ensure that your image fits the picturebox.

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

What this line of code does:

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.

Working with the other toolbox controls

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:

1. What is the difference between a button and a radio button?


2. What is the difference between a label and a textbox?
3. What are the roles of Properties Window and Solution Explorer?
4. Can we modify the code or design when the program is running?
5. What is use of a Groupbox?
6. What is the difference between the properties name and text?
7. For the given GUI, write code so that when a button (with image background) is clicked, the label
shows appropriate text.

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.

Data Type Size


Integer 32 Bit
Double 64 Bit
String 16 Bit per
character

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 order to declare a variable, we use the syntax:

Dim <var_name> As <Data type>

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:

Dim stu_name As String

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:

(i) Arithmetic Operators

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

(ii) Relational or Comparison Operators

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

(iii) Logical Operators

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

These operators also return true or false after evaluating an expression.

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.

Answer these questions:

1. What is the use of = operator in VB?


2. What are keywords?
3. What is the meaning of a variable? What is variable declaration?
4. Explain practical uses for the Mod operator and the integer division operator.
5. What is the use of Val()?
6. Design an addition tutor GUI along these lines: Two random numbers should be generated in the
range 0 to 5 and displayed on two labels. The user should give the answer and check whether it is
correct by clicking on a button. What code should be given?

13
Introduction to Control Structures in VB 2015

Types of control structures:


In any programming language, the flow of execution is controlled based on the structure of the program. In
general, there are three types of control structures:
1. Sequential
2. Decision or Selection
3. Loop or Repetitive
Sequential Structure: Here the statements of the program are given one after the other. As the name
suggests, the control moves from statement to statement in order.
Example: Flowchart that accepts two numbers from user and adds the total and displays it

Start

Input 2 numbers a,b

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.

Design of the GUI:

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

Input 2 numbers a,b

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.

Syntax of IF-THEN in VB:

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.

If Val(TextBox1.Text) > 0 Then

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.

Syntax of IF-ELSE in VB:

If <condition> Then

<Statements>

Else

<Statements>

End If

For the same example as given above, our code will change as follows:

If Val(TextBox1.Text) > 0 Then

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:

Understanding the 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-ElseIf-Else Statement Syntax:

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:

Random Number Generator in VB:

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)

To create a random number in the range 0 to 10, we give the assignment:

Y = Int(Rnd()*10)

Example of Rnd() in a program that creates a virtual dice:

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:

Understanding the 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.

Syntax for Select Case structure:


Select Case <variable>
Case <value1>
<statements to be executed if value1 matches variable>
Case <value2>
<statements to be executed if value2 matches variable>
Case <value3>
<statements to be executed if value3 matches variable>
:
.
Case Else
<statements to be executed if none of the values match variable>
End Select

Select Case Example


GUI that accepts the age of the user and prints appropriate message based on the table given below.

Age Message

1 to 5 Winnie the Pooh and Friends

6 to 10 Geronimo Stilton

11 to 15 Harry Potter

16 to 22 It‟s study time

23 to 50 Work, work and more work!

51 to 100 Enjoy Life!

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:

Understanding the code


We need a variable x that will store the age of the user. Declare x using the Dim statement and assign the
value entered by user in the textbox to x. Since x is a numeric value, we need to use the Val() function that
extracts the number from the text.
In Select Case, we can give range of values as cases by using the To keyword. When the case is 1 To 5,
the ages 1,2,3,4 and 5 come under this case and whatever statements are present below it will be
executed. So, for any of the ages mentioned above, the output would be “Winnie Pooh and Friends”. If we
had to use If-ElseIf-Else structure for this GUI, we have to use the test condition If (x >= 1 And x <= 5)
Then….

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.

Flowchart to print the 1 to 10 using Entry 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.

For Loop Example 1

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.

5. Type the code as shown here.

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.

For Loop Example - 2


GUI to print odd numbers from 100 to 0 in descending order using For loop:

Design the GUI as shown in the figure below.


Here a textbox has been used instead of a label. Change the multiline property to True and under the Scroll
bars, choose vertical.
Add the button which will generate the odd numbers.

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.

For Loop Example - 3


GUI to display different images using one PictureBox in a For loop

Design:

26
Code:

Expected Output:

Understanding the code:


The images have to be in the same location with the same extensions in order for them to be uploaded
using For loop. In this example, the images have been named as pic1.png, pic2.png, pic3.png and
pic4.png. The names are the same except for the number values associated with them. Using this, we can
use a variable that varies from 1 to 4 as part of the image name.
PictureBox1.Image = System.Drawing.Image.FromFile("C:\Users\Dell\Pictures\Saved Pictures\pic" & i &
".png")
In the above lines of code, the path name to the folder and the beginning of the image name (pic) is
enclosed in double quotes. The variable i will vary depending on the iteration and is added to the common
name of the path. Since the extension is png for all the images, “.png” is included in the end as part of the
path name to the file.
Message box is needed to make the user see the current picture. Only when the message box is closed will
the next i value be calculated and the next image will be uploaded. Without the message box, only the last
image will be displayed.

27
Do-While-Loop in VB

Syntax for Do-While-Loop:


Do While <condition>
<statements>
Loop
The Do While loop is also entry controlled as the variable is tested against the condition at the start of the
loop. If the condition is passed then the statements in the loop are executed. The Loop statement causes
control to move back to the beginning of the loop for next iteration.

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:

Do While z <= 240


TextBox1.Text = TextBox1.Text & z & vbCrLf
z=z+2
Loop

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

GUI to generate the multiplication table for a given number n by user:


The controls used are a label, a listbox, two buttons and a textbox. The label gives an instruction to the
user. The input is accepted using the textbox. Button1 generates the multiples and places them in the
listbox and Button2 closes the application once the user is done.

29
Code for the GUI:

Understanding the code

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

When Exit Button is clicked, the GUI should close.

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:

1. Write the syntax for If-ElseIf-Else structure.


2. How many blocks of statements are executed in an If-ElseIf-Else structure? Give reason for your
answer.
3. How can we use a TextBox for displaying multiline output?
4. How can a ListBox be used to display multiline output?
5. What is the use of Case Else in Select Case structure?
6. Differentiate between entry controlled loop and exit controlled loop?
7. What is the role of the ampersand operator?
8. What is the syntax for Do-While-Loop structure?
9. Differentiate between sequential and decision control structure.
10. Draw the flowchart for loop structure.
11. Write the code for a GUI that accepts temperature and based on the value, prints message like „Hot
day!‟, „Wear a jacket!‟ and „It is a fine day to be out!‟
12. When will this line of code be useful?
TextBox1.Text = “”

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.

Steps in connecting a VB application to an Access database:

1. Create the given table of data in Access and save it.


ID Emp_ID First_Name Last_Name Email Address Office_Phone Department
1 210 Shyam Srinivas ssrinivas@abc.co.in 080-2124-5678 HR
2 126 Anita Dev adev@abc.co.in 080-2124-5578 IT
3 342 Kurien Gupta kgupta@abc.co.in 080-2124-5555 Admin
4 567 Barghav Khanna bkhanna@abc.co.in 022-8990-2323 HR
5 121 Anthony Raj araj@abc.co.in 022-8990-2324 IT
6 899 Karim Khan kkhan@abc.co.in 044-6589-1212 IT
7 345 Elsa Peters epeters@abc.co.in 022-8990-2467 IT
8 233 Varsha Ram vram@abc.co.in 044-6589-1111 Admin
9 590 Sunita Misra smisra@abc.co.in 044-6589-1119 HR
10 448 Farah Aftab faftab@abc.co.in 044-6589-1120 HR

2. Open Visual Studio 2015 and create a new project titled Employee_Form.

3. Click on Project -> Add a New Data Source

4. The data source wizard opens. Click on Database and then on Next.

5. Choose Dataset model and click on Next again.

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.

10. Click on Save All to save the project.

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:

How do we use Data Sources Window to create database objects on a Form?

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:

1. Create a new project called Menustrip


2. Drag and drop a menustrip control onto the form. It will appear underneath the Form like the Timer.

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.

When we run the application, clicking on Exit closes the application.

Creating shortcuts to menu options

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.

Let us add a Help menu for this application.

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

You might also like