0% found this document useful (0 votes)
13 views112 pages

Prog 2 VB. Net Module v2

The document is a course module for Computer Programming II at President Ramon Magsaysay State University, focusing on VB.NET programming. It covers various topics including interface design, data management, and database integration, with a structured outline of chapters and lessons. The course aims to enhance students' skills in creating dynamic applications and understanding object-oriented programming concepts.

Uploaded by

jhegs tindugan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views112 pages

Prog 2 VB. Net Module v2

The document is a course module for Computer Programming II at President Ramon Magsaysay State University, focusing on VB.NET programming. It covers various topics including interface design, data management, and database integration, with a structured outline of chapters and lessons. The course aims to enhance students' skills in creating dynamic applications and understanding object-oriented programming concepts.

Uploaded by

jhegs tindugan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 112

CC 103 – COMPUTER

PROGRAMMING II

This is a property of
PRESIDENT RAMON MAGSAYSAY STATE UNIVERSITY
NOT FOR SALE
Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Copyright. Republic Act 8293 Section 176 provides that “No copyright shall subsist in
any work of the Government of the Philippines. However, prior approval of the
government agency or office wherein the work is created shall be necessary for
exploitation of such work for profit. Such an agency of office may, among other things,
impose as a condition the payment of royalties.

Borrowed materials included in this module are owned by their respective copyright
holders. Every effort has been exerted to reach and seek permission to use these
materials from their respective copyright owners. The University and authors do not claim
ownership over them.

Learning Module Development Team

Assigned Chapter Title Author

Chapter 1 Introduction to Visual Basic

Chapter 2 Designing the Interface

Chapter 3 Writing the Code


Chapter 4 Managing VB.Net Data
Mathematical Operations and
Chapter 5
String Manipulations
Chapter 6 VB.Net - Basic Controls
DANIEL A. BACHILLAR
Chapter 7 Functions
Chapter 8 Conditional Statements

Chapter 9 Looping Statements

Chapter 10 Arrays

Chapter 11 Menus and Toolbar

Chapter 12 Working with Database

Computer Programming II Page 2 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

TABLE OF CONTENTS

COURSE OVERVIEW Page 6

CHAPTER 1: INTRODUCTION TO VISUAL BASIC


Lesson 1: A Brief Description Page 7
Lesson 2: Navigating the Visual Studio IDE Page 8
Lesson 3: Concept of Visual Basic.Net Programming Page 11

CHAPTER 2: DESIGNING THE INTERFACE


Lesson 1: Adding Controls to the Form Page 15
Lesson 2: Setting Control Properties in Properties Window Page 16
Lesson 3: Setting Control Properties using Code Page 18

CHAPTER 3: WRITING THE CODE


Lesson 1: The Event Driven Programming Page 21
Lesson 2: The Code Structure of an Event Procedure Page 22

CHAPTER 4: MANAGING VB.NET DATA


Lesson 1: Data Types Page 26
Lesson 2: Variables Page 28
Lesson 3: Constants Page 31

CHAPTER 5: MATHEMATICAL OPERATIONS AND


STRING MANIPULATIONS
Lesson 1: Performing Mathematical Operations Page 33
Lesson 2: String Manipulation Using + and & Signs Page 34
Lesson 3: String Manipulation Using Built-in Functions Page 36

Computer Programming II Page 3 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

CHAPTER 6: VB.NET - BASIC CONTROLS


Lesson 1: Control Properties Page 39
Lesson 2: Control Methods Page 40
Lesson 3: Control Events Page 40
Lesson 4: Basic Controls Page 41

CHAPTER 7: FUNCTIONS
Lesson 1: MsgBox() Function Page 53
Lesson 2: InputBox() Function Page 56
Lesson 3: String Functions Page 57
Lesson 4: Formatting Functions Page 61

CHAPTER 8: CONDITIONAL STATEMENTS


Lesson 1: If … Then Page 66
Lesson 2: If … Then … Else Page 67
Lesson 3: Ladderized If’s Page 68
Lesson 4: Nested If Page 70
Lesson 5: Select Case Page 72

CHAPTER 9: LOOPING STATEMENTS


Lesson 1: For…Next Loop Page 76
Lesson 2: While…End While Loop Page 77
Lesson 3: Do Loop Page 78
Lesson 4: Nested Loop Page 81

CHAPTER 10: ARRAYS


Lesson 1: Introduction to Arrays Page 84
Lesson 2: One-dimensional Array Page 84
Lesson 3: Two-dimensional Array Page 86

Computer Programming II Page 4 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

CHAPTER 11: MENUS AND TOOLBAR


Lesson 1: Adding Menus Page 90
Lesson 2: Adding Toolbar Icons Page 95

CHAPTER 12: WORKING WITH DATABASE


Lesson 1: ADO.Net Object Model Page 99
Lesson 2: Data Provider Page 100
Lesson 3: DataSet Page 101
Lesson 4: Connecting to a Database Page 102
Lesson 5: Storing, Retrieving, and Manipulating Records Page 106

Computer Programming II Page 5 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

COURSE OVERVIEW
Introduction

This course is designed to expand students' knowledge and skills in software

development using the VB.NET programming language. This course builds upon

introductory programming concepts and delves into more advanced topics, focusing on

creating dynamic, data-driven applications with professional-quality user interfaces.

Students will explore the full lifecycle of application development, from designing intuitive

interfaces to writing efficient and maintainable code, managing data, and integrating

database functionalities. By engaging with a variety of practical exercises and real-world

projects, students will enhance their problem-solving abilities and prepare for complex

programming challenges in the industry.

Course General Objectives

By the end of this course, students will be able to:

 Understand and apply techniques for managing data in VB.NET applications,


including variables, data types, mathematical operations, string manipulations, and
arrays.

 Create intuitive and user-friendly graphical interfaces using Windows Forms and
basic controls, emphasizing usability and user experience design principles.

 Write well-structured and efficient VB.NET code, incorporating functions,


conditional statements, and looping constructs to enhance code readability and
reusability.

 Connect applications to databases using ADO.NET, perform essential database


operations (CRUD), and ensure data integrity and security within the application.

 Implement advanced features such as menus, toolbars, and custom controls to


improve application navigation and functionality, providing a comprehensive user
experience.

Computer Programming II Page 6 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

CHAPTER 1
INTRODUCTION TO VISUAL BASIC

Lesson 1: A Brief Description

Visual Basic.Net is a component of the Visual Studio that is owned by Microsoft. It is

almost similar to Visual Basic 6.0, but has added many new features. Visual Basic has gone

through many phases of development since the days of BASIC that was built for DOS. BASIC

stands for Beginners' All-purpose Symbolic Instruction Code. The program code in Visual

Basic resembles the English language.

Different software companies had produced many different versions of BASIC for DOS,

such as Microsoft QBASIC, QUICKBASIC, GWBASIC, and IBM BASICA and more. Then,

Microsoft launched the first graphical BASIC, Visual Basic Version 1 in 1991. It is GUI based and

especially developed for MS window. Since then Microsoft slowly phased out the DOS versions

of BASIC and completely replaced them by Visual Basic.

Visual Basic was initially a functional or procedural programming language until the

popular Visual Basic 6. Then, Microsoft transformed Visual Basic into a more powerful object

oriented programming language by launching Visual Basic.Net, from Visual Studio 2002 to the

latest Visual Studio 2022 version.

Visual Basic.Net is a full-fledged Object-Oriented Programming (OOP) Language; it has

caught up with other OOP languages such as C++, Java, C# and others. However, you do not

have to know OOP to learn VB.Net. In fact, if you are familiar with Visual Basic 6, you can learn

VB.Net effortlessly because the syntax and interface are almost similar. Visual Studio 2022

Community Edition is available for free download from the Microsoft site as shown below:

https://visualstudio.microsoft.com/downloads/

Computer Programming II Page 7 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Lesson 2: Navigating the Visual Studio IDE

The Start Page

When you launch Visual Studio 2022, you can see the start page of the Integrated

Development Environment, as shown in Figure below.

The IDE consists of a few panes, namely:

 Recent/Older pane shows the list of projects that you have created recently.

 Clone a repository will allow you to collaborate on existing codes.

 Open a local folder option to open your code in Visual Studio to develop code

without projects or solutions.

 The Continue without code option will open the Visual Studio development

environment without any specific project or code loaded. You might choose this

option to join a Live Share session or attach to a process for debugging.

Computer Programming II Page 8 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

The Create New Project Dialog

The Create a new project window opens and shows several project templates. A

template contains the basic files and settings required for a given project type. Here, you

can search, filter, and pick a project template. The Create a new project window also

shows a list of your recently used project templates as shown in the figure below.

As we are going to create a standard Windows application, we will select Windows

Forms Application. In the Configure your new project window, you can change the

default project name and location, and then select Next.

In the Additional information window, ensure that .NET 8.0 appears in the

Framework dropdown menu, and then select Create. The project will then be created and

loaded in Visual Studio.

Computer Programming II Page 9 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

The Designer Interface

The VS2022 IDE Designer interface is shown in figure below. The Designer

consists of the Menu bar, the Toolbars, an empty Form, the Solution Explorer and the

Properties Window.

The Designer Environment that appears on your PC or laptop might not be the

same here, depending how you customize it. You can customize your interface by

dragging the windows and dock them or let them float. You can also hide them. To dock

a window, you drag its title bar and drag it to the side, top or bottom of the workspace or

another window. You can also resize the docked window by dragging the side of the

window. To free up and float the docked window, you just drag its title bar and move it

away from the edge of the workspace. If you do not see a particular window such as the

properties window, you can click on the View menu and click the name of the window, that

particular window will appear.

Computer Programming II Page 10 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

 Form-The Form is the first place to build your application. It is the place to design the user

interface.

 Solution Explorer -The solution explorer displays a list of projects, files and other

components that you can easily browse and access. For example, it displays My Project

and Form1.vb in Figure above.

 Properties Window- This is the place to set the properties of the objects in your

application. The objects include the default form and the controls you place in the form.

We will learn more about setting properties later.

Lesson 3: Concept of Visual Basic.Net Programming

The main difference between VB.Net and Visual Basic 6 is that it is a full Object Oriented

Programming Language while VB6 may have OOP capabilities, it is not fully object oriented. In

order to qualify as a fully object oriented programming language, it must have three core

technologies namely encapsulation, inheritance and polymorphism.

 Encapsulation refers to the creation of self-contained modules that bind processing

functions to the data. These user-defined data types are called classes. Each class

contains data as well as a set of methods, which manipulate the data. The data

components of a class are called instance variables and one instance of a class is an

object. For example, in a library system, a class could be member, and John and Sharon

could be two instances (two objects) of the library class.

 Inheritance. Classes are created according to hierarchies, and inheritance allows the

structure and methods in one class to be passed down the hierarchy. That means less

programming is required when adding functions to complex systems. If a step is added at

the bottom of a hierarchy, then only the processing and data associated with that unique

Computer Programming II Page 11 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

step needs to be added. Everything else about that step is inherited. The ability to reuse

existing objects is a major advantage of object technology.

 Polymorphism. Object-oriented programming allows procedures about objects to be

created whose exact type is not known until runtime. For example, a screen cursor may

change its shape from an arrow to a line depending on the program mode. The routine to

move the cursor on screen in response to mouse movement would be written for "cursor,"

and polymorphism allows that cursor to take on whatever shape is required at run time. It

also allows new shapes to be integrated easily.

VB.Net is a fully Object Oriented Programming Language, just like other OOP such as

C++ and Java. It is different from the earlier versions of VB because it focuses more on the data

itself while the previous versions focus more on the actions. Previous versions of VB are

procedural or functional programming language. Some other procedural programming languages

are C, Pascal and Fortran.

VB.Net allows users to write programs that break down into modules. These modules

represent the real-world objects; we also call them classes or types. An object can be created out

of a class, it is an instance of the class. A class can also comprise subclass. For example, apple

tree is a subclass of the plant class and the apple in your backyard is an instance of the apple

tree class.

Another example is student class is a subclass of the population class while a student with

the name John is an instance of the student class. A class consists of data members as well as

methods. In VB.Net, the program structure to define a population class can be written as follows:

Computer Programming II Page 12 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

After you have created the population class, you can create a subclass that inherits the

attributes or data from the population class. For example, you can create a student class that is

a subclass of the population class. Under the student class, you do not have to define any data

fields that were already defined under the population class; you only have to define the data fields

that are different from an instance of the population class. For example, you may want to include

StudentID and Address in the student class. The program code for the StudentClass is as follows:

Computer Programming II Page 13 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Activity Sheet

1. Create a timeline highlighting the evolution of Visual Basic.Net. Include major versions
and significant changes in each version.

2. Draw the Visual Studio IDE and describe ten (10) features or tools.

Computer Programming II Page 14 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

CHAPTER 2
DESIGNING THE INTERFACE

Lesson 1: Adding Controls to the Form

The first step in creating a new VB.Net project is to design

the interface of the application. You design an interface by adding

controls to the form and then set their properties. You can add

controls from the Toolbox. To see the Toolbox window, you can

use the short-cut keys Ctrl+Alt+X or click on the Toolbox icon on

the toolbar on top of the designer environment. The Toolbox

consists of many useful controls such as Button, TextBox, Label,

ComboBox, CheckBox and more.

The Visual Basic Control Toolbox consists of all the

controls essential for developing a VISUAL BASIC.Net

application. Controls in VB.Net are useful tools that can perform

various tasks. We categorized into Common Controls,

Containers, Menus, Toolbars, Data, Components, Printings and

Dialogs. Now, we will focus on the common controls. Some of the

most used common controls are Button, Label, ComboBox,

ListBox, PictureBox, TextBox and more. To add a control to the

form, just drag the particular control and drop it into the form. After

putting it into the form, you can change its size and position easily.

You can add as many controls as you want, but avoid crowding

the form.

Computer Programming II Page 15 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Lesson 2: Setting Control Properties in Properties Window

To customize the interface to the users, you need to set the properties of the controls,

from the form itself to the controls you add to the form. You can set the properties of the controls

in the properties window at design time or by using the code. We shall learn how to set the control

properties using the properties window first.

To set the properties of an object, right click on the

object and choose properties in the dialog that appears to

view the properties window. In the properties window, you

can change the values of the properties that appear in a

dropdown list. It is a typical Properties window for a form.

The default text of the Text property is Form1, its default

name is also Form1. You can change the title of the text to

whatever title you like by editing the text.

The properties of the object appear in a list in the

left column while the items listed in the right column

represent the states or values of the properties. You can

set the properties by highlighting the items in the right

column then change them by typing or by selecting

options. For example, to change the form's title to any

name that you like, simple click in the box on the right of

the Text property and type in the new name. In the

properties window, the item appears at the top part is the

currently selected object.

Computer Programming II Page 16 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Example: Creating a simple program that display a welcoming message

In this example, we will create a simple program that will display a welcome message

when you load the form. First, change the properties of the form as follows:

PROPERTY VALUE
Name Form1
Backcolor (Select a background color of your choice)
Font Microsoft Sans Serif Size 10 and Bold
Forecolor White (The color of the displayed text)
Maximizebox False (Cannot be maximized)
Text Visual Studio 2022

Next, insert a label into the form and set its properties as follows:

PROPERTY VALUE
AutoSize False
Name Msglbl
BackColor (Select a background color of your choice)
BorderStyle FixedSingle
Font Microsoft Sans Serif Size 10 and Bold
ForeColor Black
Size 239, 32
Text (Remove or Blank It)

Next, click on the Form and enter the following code:

Now press F5 to run the program, you will see the message displayed on the label, as

shown in Figure below:

Computer Programming II Page 17 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Lesson 3: Setting Control Properties using Code

You can also change the properties of the object using code. The syntax to manipulate

the properties of an object is:

For Example:

The above code sets the text property of TextBox1 to display the text “Welcome to VB.Net”

and set the value of TextBox2 to 100. Other properties you can change to give special effects at

runtime are color, shape, animation effect and so on. For example, the following code will change

the form color to yellow every time the form is loaded. VB.Net uses RGB (Red, Green, Blue) to

determine the colors. The RGB code for yellow is 255, 255, 0. Me in the code refers to the current

form and Backcolor is the property of the form's background color. The formula to assign the RGB

color to the form is Color.FormArbg (RGB code). Now, click on the form to go into the code

Computer Programming II Page 18 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

window. Next, enter the following code between the opening statement Private Sub and the

closing statement End Sub, as shown below.

Now Press F5 and you will see a form appear with a yellow background.

You may also use the following procedure to produce the

same effect:

Here are some of the common colors and the corresponding RGB codes. You can always

experiment with other combinations, but remember the maximum number for each color is 255

and the minimum number is 0. The figure below shows some of the common colors with their

corresponding codes.

Computer Programming II Page 19 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Activity Sheet

1. Design a user interface for a basic application by adding various controls like buttons, text
boxes, and labels to the form.

2. Customize the appearance of the controls added in the previous activity by modifying
properties like size, color, and text through the Properties window.

3. Write code to dynamically change the properties of controls based on user interactions,
such as changing the color of a button when clicked.

Computer Programming II Page 20 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

CHAPTER 3
WRITING THE CODE

Lesson 1: The Event Driven Programming

VB.Net is an object oriented and event driven

programming language. In fact, all windows

applications are event driven. Event driven means

the user decides what to do with the program,

whether he or she wants to click the command

button, enter text in a text box, or close the

application and more.

An event is related to an object, it is an

incident that happens to the object due to the action

of the user, such as a click or pressing a key on the

keyboard. A class contains events as it creates

instant of a class or an object.

When we start a windows application in

VB.Net in previous chapters, we will see a default

form with the Form1 appears in the IDE. Form1 is the

Form1 Class that inherits from the Form class

System.Windows.Forms.Form.

The other events associated with the Form1 class are click, DoubleClick, DragDrop, Enter

and more, as shown in Figure below (It appears when you click on the upper right pane of the

code window).

Computer Programming II Page 21 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Lesson 2: The Code Structure of an Event Procedure

Now you are ready to write the code for the event procedure so that it will do something

more than loading a blank form. The structure of the code takes the following form:

You have to enter the code between Private Sub and End Sub.

Computer Programming II Page 22 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

There are variations of the structure such as:

Let us enter the following code:

When you press F5 to run the program, the output is shown in Figure below:

Computer Programming II Page 23 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

The first line of the code will change the title of the form to “My First VB.Net Program”, the

second line will change the foreground object to yellow( in this case, it is a label that you insert

into the form and change its name to Foreground) and the last line changes the background to

blue color. The equal sign in the code is to assign something to the object, like assigning yellow

color to the foreground of the Form1 object (or an instance of Form1). Me is the name given to

the Form1 class. We can also call those lines as Statements. Therefore, the actions of the

program will depend on the statements entered by the programmer. Here is another example:

In this example, you insert one command button into the form and rename its caption as

Show Hidden Names. The keyword Dim is to declare variables name1, name2 and name3 as

string, which means they can only handle text. The function MsgBox is to display the names in a

message box that are joined together by the "&" signs. The output is shown in Figure below:

Computer Programming II Page 24 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Activity Sheet

1. Create a form with different controls (buttons, text boxes, etc.) and implement event
handlers for different events (click, text change) to understand how event-driven
programming works.

Computer Programming II Page 25 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

CHAPTER 4
MANAGING VB.NET DATA

Lesson 1: Data Types

In our daily life we come across many types of data. For example, we need to handle data

such as names, addresses, money, dates, stock quotes, statistics and more every day. Similarly,

in Visual Basic.Net, we have to deal with all sorts of data; some are numeric in nature while some

are in the form of text or other forms. VB.Net divides data into different types so that it is easier to

manage when we need to write the code involving those data.

Visual Basic classifies the information mentioned above into two major data types; namely

the numeric data types and the non-numeric data types.

Numeric Data Types

Numeric data types are types of data that consist of numbers, which you can compute

them mathematically with various standard operators such as add, minus, multiply, divide and so

on. Examples of numeric data types are your examination marks, your height and your weight,

the number of students in a class, share values, price of goods, monthly bills, fees and more.

TYPE STORAGE RANGE OF VALUES


Byte 1 byte 0 to 255
Integer 2 bytes -32,768 to 32,767
Long 4 bytes -2,147,483,648 to 2,147,483,648
Single 4 bytes -3.402823E+38 to -1.401298E-45 for negative values
1.401298E-45 to 3.402823E+38 for positive values.
Double 8 bytes -1.79769313486232e+308 to -4.94065645841247E-324 for
negative values
4.94065645841247E-324 to 1.79769313486232e+308 for
positive values.
Currency 8 bytes -922,337,203,685,477.5808 to 922,337,203,685,477.5807
Decimal 12 bytes +/- 79,228,162,514,264,337,593,543,950,335 if no decimal is
use
+/- 7.9228162514264337593543950335 (28 decimal places).

Computer Programming II Page 26 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

In Visual Basic, we divide numeric data into seven types, depending on the range of values

they can store. Calculations that only involve round figures or data that do not need precision can

use Integer or Long integer in the computation. Programs that require high precision calculation

need to use Single and Double decision data types, we also call them floating-point numbers. For

currency calculation, you can use the currency data types. Lastly, if even more precision is

required which involve many decimal points, we can use the decimal data types.

Non-numeric Data Types

Nonnumeric data types are data that cannot be manipulated mathematically using

standard arithmetic operators. The non-numeric data comprises text or string data types, the Date

data types, the Boolean data types that store only two values (true or false), Object data type and

Variant data type.

TYPE STORAGE RANGE OF VALUES


String (Fixed Length) Length of string 1 to 65,400 characters
String (Variable Length) Length + 10 bytes 0 to 2 billion characters
Date 8 bytes January 1, 100 to December 31, 9999
Boolean 2 bytes True or False
Object 4 bytes Any embedded object
Variant (Numeric) 16 bytes Any value as large as Double
Variant (Text) Length+22 bytes Same as variable-length string

Suffixes for Literals

Literals are values that you assign to a data. In some cases, we need to add a suffix

behind a literal so that VB.NET can handle the calculation more accurately. For example, we can

use num=1.3089# for a Double type data.


SUFFIX DATA TYPE
& Long
! Single
# Double
@ Currency

Computer Programming II Page 27 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

In addition, we need to enclose string literals within two quotations and date and time

literals within two # sign. Strings can contain any characters, including numbers. The following

are few examples:

memberName="Turban, John."

TelNumber="1800‐900‐888‐777"

LastDay=#31‐Dec‐00#

ExpTime=#12:00 am#

Lesson 2: Variables

Variables are like mail boxes in the post office. The contents of the variables change every

now and then, just like the mail boxes. In term of VB.NET, variables are areas allocated by the

computer memory to hold data. Like the mail boxes, each variable must be given a name. To

name a variable in Visual Basic, you have to follow a set of rules.

Variable Names

The following are the rules when naming the variables:

 It must be less than 255 characters

 No spacing is allowed

 It must not begin with a number

 Period is not permitted

Examples of valid and invalid variable names are displayed in Table below:

VALID INVALID
My_Name My.Name
ThisDate 1NewDate
Long_Name_Can_beUSE His&Her

Computer Programming II Page 28 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Declaring Variables

In Visual Basic, one needs to declare the variables before using them by assigning names

and data types. If you fail to do so, the program will show an error. They are normally declared in

the general section of the codes' windows using the Dim statement.

The format is as follows:

Example:

You may also combine them in one line, separating each variable with a comma, as follows:

For string declaration, there are two possible formats, one for the variable-length string and

another for the fixed-length string. For the variable-length string, just use the same format as

example 4.1 above. However, for the fixed-length string, you have to use the format as shown

below:

Computer Programming II Page 29 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Dim VariableName as String * n,

where n defines the number of characters the string can hold.

Example:

yourName can holds no more than 10 Characters.

Assigning Values to Variables

After declaring various variables using the Dim statements, we can assign values to those

variables.

The general format of an assignment is:

The variable can be a declared variable or a control property value. The expression could

be a mathematical expression, a number, a string, a Boolean value (true or false) and more. The

following are some examples:

Computer Programming II Page 30 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Lesson 3: Constants

Constants are different from variables in the sense that their values do not change during

the running of the program.

The format to declare a constant is:

Example:

Computer Programming II Page 31 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Activity Sheet

1. Develop a small application that demonstrates the use of different data types (e.g., Integer,
String, Boolean) and allows users to input and display values.

2. Write a program that performs basic arithmetic operations using variables and displays
the results. Include input from the user to practice variable assignment.

3. Create a program that uses constants for fixed values (e.g., mathematical constants).

Computer Programming II Page 32 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

CHAPTER 5
MATHEMATICAL OPERATIONS AND STRING MANIPULATIONS

Lesson 1: Performing Mathematical Operations

Computers can perform mathematical calculations much faster than human beings.

However, the computer itself will not be able to perform any mathematical calculations without

receiving instructions from the programmer. In VB.NET, we can write code to instruct the

computer to perform mathematical calculations such as addition, subtraction, multiplication,

division and other kinds of arithmetic operations. In order for VB.NET to carry out arithmetic

calculations, we need to write code that involves the use of various arithmetic operators. The

VB.NET arithmetic operators are very similar to the normal arithmetic operators, only with slight

variations. The plus and minus operators are the same while the multiplication operator use the *

symbol and the division operator use the / symbol. The list of VB.NET arithmetic operators are

shown in table below:

OPERATOR MATHEMATICAL FUNCTION EXAMPLE


+ Addition 1+2=3
- Subtraction 4-1=3
* Multiplication 4*3=12
/ Division 12/4=3
^ Exponential 2^4=16
Mod Modulus (return the remainder 15 Mod 4=3
from an integer division)
\ Integer Division (discards the 19\4=4
decimal places)

Example:

In this program, you need to insert two Textboxes, four labels and one button. Click the

button and enter the code as shown below. When you run the program, it will perform the four

basic arithmetic operations and display the results on the four labels.

Computer Programming II Page 33 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Lesson 2: String Manipulation Using + and & Signs

String manipulation is an important part of programming because it helps to process data

that come in the form of non-numeric types such as name, address, city, book title and etc.

Strings can be manipulated using the & sign and the + sign, both perform the string

concatenation which means combining two or more smaller strings into a larger string. For

example, we can join "Visual" and "Basic" into "Visual Basic" using "Visual"&"Basic" or "Visual

"+"Basic", as shown below:

Computer Programming II Page 34 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Example:

This code will produce an error because of data mismatch. However, using & instead of + will be

all right. You can also combine more than two strings to form a larger string, like the following

example:

Running the above program will produce the following output:

Computer Programming II Page 35 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Lesson 3: String Manipulation Using Built-in Functions

A function is similar to a normal procedure but the main purpose of the function is to accept

a certain input and return a value, which is passed on to the main program to finish the execution.

VB.NET has numerous built-in string manipulation functions but we will only discuss a few here.

You will learn more about these functions in later Chapters.

Len Function

The length function returns an integer value that is the length of a phrase or a

sentence, including the empty spaces. The format is: Len (“Phrase”)

Example:

The output:

Computer Programming II Page 36 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Right Function

The Right function extracts the right portion of a phrase. The format for Visual

Basic 6 is: Right (“Phrase”, n) where n is the starting position from the right of the phase

where the portion of the phrase is going to be extracted.

For example:

However, this format is not applicable in VB.NET. In VB.NET, we need to use the following

format:

The reason of using the full reference is because many objects have the Right

properties so using Right on its own will make it ambiguous to VB.NET. The program

below will return four right most characters of the phrase entered into the textbox:

Left Function

The Left function extract the left portion of a phrase. The format is:

Microsoft.VisualBasic.Left("Phrase",n) where n is the starting position from the left of

the phase where the portion of the phrase is going to be extracted.

For example:

Computer Programming II Page 37 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Activity Sheet

1. Design a simple calculator application that performs basic arithmetic operations (addition,
subtraction, multiplication, division) and displays the results.

2. Write a program that concatenates strings using both + and & operators and compares
their outputs.

3. Create a text processing program that uses built-in functions to manipulate and format
strings.

Computer Programming II Page 38 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

CHAPTER 6
VB.NET - BASIC CONTROLS

An object is a type of user interface element you create on a Visual Basic form by using a

toolbox control. In fact, in Visual Basic, the form itself is an object. Every Visual Basic control

consists of three important elements:

 Properties which describe the object,

 Methods cause an object to do something and

 Events are what happens when an object does something.

Lesson 1: Control Properties

All the Visual Basic Objects can be moved, resized or customized by setting their

properties. A property is a value or characteristic held by a Visual Basic object, such as Caption

or Fore Color.

Properties can be set at design time by using the Properties window or at run time by

using statements in the program code:

where

Object is the name of the object you're customizing.

Property is the characteristic you want to change.

Value is the new property setting.

For example:

You can set any of the form properties using Properties Window. Most of the properties

can be set or read during application execution. You can refer to Microsoft documentation for a

complete list of properties associated with different controls and restrictions applied to them.

Computer Programming II Page 39 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Lesson 2: Control Methods

A method is a procedure created as a member of a class and they cause an object to do

something. Methods are used to access or manipulate the characteristics of an object or a

variable. There are mainly two categories of methods you will use in your classes:

 If you are using a control such as one of those provided by the Toolbox, you can call any

of its public methods. The requirements of such a method depend on the class being used.

 If none of the existing methods can perform your desired task, you can add a method to a

class.

For example, the MessageBox control has a method named Show, which is called in the code

snippet below:

Lesson 3: Control Events

An event is a signal that informs an application that something important has occurred.

For example, when a user clicks a control on a form, the form can raise a Click event and call a

procedure that handles the event. There are various types of events associated with a Form like

click, double click, close, load, resize, etc.

Following is the default structure of a form Load event handler subroutine. You can see

this code by double clicking the code which will give you a complete list of the all events

associated with Form control:

Computer Programming II Page 40 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Here, Handles MyBase.Load indicates that Form1_Load() subroutine handles Load

event. Similar way, you can check stub code for click, double click. If you want to initialize some

variables like properties, etc., then you will keep such code inside Form1_Load() subroutine.

Here, important point to note is the name of the event handler, which is by default Form1_Load,

but you can change this name based on your naming convention you use in your application

programming.

Lesson 4: Basic Controls

VB.Net provides a huge variety of controls that help you to create rich user interface.

Functionalities of all these controls are defined in the respective control classes. The control

classes are defined in the System.Windows.Forms namespace. The following table lists some

of the commonly used controls.

TOOL DESCRIPTION
Forms The container for all the controls that make up the user interface.
TextBox It represents a Windows text box control.
Label It represents a standard Windows label.
Button It represents a Windows button control.
ListBox It represents a Windows control to display a list of items.
ComboBox It represents a Windows combo box control.
RadioButton It enables the user to select a single option from a group of choices
when paired with other RadioButton controls.
CheckBox It represents a Windows CheckBox.
PictureBox It represents a Windows picture box control for displaying an image.
ProgressBar It represents a Windows progress bar control.

Computer Programming II Page 41 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

ScrollBar It Implements the basic functionality of a scroll bar control.


DateTimePicker It represents a Windows control that allows the user to select a date and
a time and to display the date and time with a specified format.
TreeView It displays a hierarchical collection of labeled items, each represented
by a TreeNode.
ListView It represents a Windows list view control, which displays a collection of
items that can be displayed using one of four different views.

Examples of Programs using the Basic Tools

TextBox, Label, Button and MessageBox

Computer Programming II Page 42 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

This program consists of four (4) Common Controls in the Toolbox with two (2)

event handlers for Button:

 btnShow_Click Event Handler. This subroutine is triggered when the

btnShow button is clicked. It displays a MessageBox with a greeting

message that includes the text entered in the TextBox. The MessageBox

was customized with an Information Icon and the Title "SAMPLE

MESSAGE BOX".

 btnClear_Click Event Handler: This subroutine is triggered when the

btnClear button is clicked. It clears the text from the TextBox using either

the Clear method or the Null String (“”). It then sets the Focus back to

the TextBox.

ComboBox, ListBox and RadioButton

Computer Programming II Page 43 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

This program is a simple pizza order form that allows the user to select the variety,

size, and crust style of a pizza. The selected options are then displayed in labels on the

form. Here's a breakdown of how it works:

 cboVariety_SelectedIndexChanged Event Handler. Triggered when the

selected item in the ComboBox changes. Updates the lblVariety label to display

the selected pizza variety.

 lstSize_SelectedIndexChanged Event Handler. Triggered when the selected

item in the ListBox changes. Updates the lblSize label to display the selected

pizza size.

Computer Programming II Page 44 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

 rbThick_CheckedChanged and rbThin_CheckedChanged Event Handlers.

Triggered when the RadioButton is checked. Updates the lblCrust label to

display either the "Thin Crust" or "Thick Crust".

 btnNew_Click Event Handler. Triggered when the "New Order" button is

clicked. Resets the selection of cboVariety, lstSize, and the RadioButtons for

crust style, then clears the text of the lblCrust label.

Timer and DateTimePicker

This program uses different visual basic tools that can be used when dealing with

Date and Time. It consists of four separate sub-programs that will be discussed below.

Computer Programming II Page 45 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

This code snippet is an event handler that updates a label to display a formatted date

when the value of a DateTimePicker control changes. The dtpBday_ValueChanged

Event Handler subroutine is triggered when the value of the DateTimePicker control is

changed by the user. It formats the selected date from the DateTimePicker and displays

it in a label.

 dtpBday - This is the DateTimePicker control where the user selects a date.

 lblBday - This is the label control where the formatted date will be displayed.

 Format(dtpBday.Value, "dddd, MMMM dd, yyyy") - This function formats the date

selected in the DateTimePicker (dtpBday.Value) to a specific string format. The format

string "dddd, MMMM dd, yyyy" represents:

- dddd: Full name of the day (e.g., "Monday")

- MMMM: Full name of the month (e.g., "January")

- dd: Day of the month (e.g., "01")

- yyyy: Full year (e.g., "2024")

When the user selects a new date in the DateTimePicker, the label will be updated to

display the date in the specified format.

Computer Programming II Page 46 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

This code snippet handles the DateChanged event of a MonthCalendar control. When

the selected date range in the calendar changes, it updates two labels to display the start

and end dates of the selected range. The MonthCalendar1_DateChanged Event

Handler subroutine is triggered when the date selection in the MonthCalendar1 control

changes. It updates the labels to show the start and end dates of the selected range.

 MonthCalendar1. This is the MonthCalendar control that allows the user to select

a date or range of dates.

 lblFrom. This label displays the start date of the selected range.

 lblTo. This label displays the end date of the selected range.

 MonthCalendar1.SelectionRange.Start. This property gets the start date of the

selected range in the MonthCalendar.

 MonthCalendar1.SelectionRange.End. This property gets the end date of the

selected range in the MonthCalendar.

When the user selects a new date range in the MonthCalendar, the lblFrom label is

updated with the start date of the selection, and the lblTo label is updated with the end

date of the selection.

This code snippet handles the Tick event of a Timer control. It updates a label to display

the current date and time every time the timer ticks. Unlike the other tools, the Timer is

not visible in the Form during the design and the runtime. This is because VB.Net controls

like the Timer runs in the background. As shown in the figure below, the Timer control

appears in the bottom of the Visual Studio IDE.

Computer Programming II Page 47 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

The tmrDateTime_Tick Event Handler subroutine is triggered every time the Timer ticks,

which occurs at intervals specified by the timer's Interval property. Then updates the text

of a label to show the current date and time.

 tmrDateTime. This is the Timer control that generates Tick events at regular

intervals.

 lblDateTime. This is the label control that will display the current date and time.

 Date.Now. This property gets the current date and time.

 Format(Date.Now). This function formats the current date and time as a string. By

default, Format will use the general date/time pattern (short date and long time).

The Timer control have limited Properties to

be configured prior to its use. However, two

(2) of the these are required for it to function

properly: Enabled and Interval. The

“Enabled” property of the timer represents is

On/Off switch while the “Interval” sets the

speed. Setting the Interval to “1000”

milliseconds means every tick of the Timer is

equivalent to One (1) second.

Computer Programming II Page 48 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

This last code snippet handles the event of a button that sets the System Date and Time

based on the values from a DateTimePicker control and a TextBox control.

 Microsoft.VisualBasic.DateString. This property sets the system date. It takes a

string in the format "MM/dd/yyyy".

 Microsoft.VisualBasic.TimeOfDay. This property sets the system time. It takes

a string representing the time.

 Format(dtpDate.Value, "MM/dd/yyyy"). This function formats the value of the

DateTimePicker (dtpDate.Value) to the required date format "MM/dd/yyyy".

 txtTime.Text. This retrieves the text from the txtTime textbox, which should

contain the time in a suitable format.

Changing the system date and time

programmatically requires Administrative

Privileges and can have significant effects

on the system and running applications. This

code should be used with caution.

Computer Programming II Page 49 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

PictureBox and ScrollBars

This code snippet provides functionality that allows the user to browse for an Image File

and display it in a PictureBox. The btnBrowse_Click Event Handler subroutine is

triggered when the "Browse Picture" button (btnBrowse) is clicked. It opens a File Dialog

(ofdPicture) to allow the user to select an image file. After the user selects an image file,

the ImageLocation property of the PictureBox (picProfile) is set to the selected file's path,

Computer Programming II Page 50 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

displaying the image. Meanwhile,

the "Clear Picture" button

(btnClear) removes the image

displayed in the PictureBox by

setting its Image property to

Nothing. An Open Dialog Box is

illustrated in this figure.

This code snippet handles the Scroll events of Horizontal and Vertical Scroll Bars to

dynamically adjust the Width and Height of the PictureBox. When the user scrolls the

Horizontal Scroll Bar (hsbWidth), the width of the PictureBox (picProfile) changes

according to the current value of the scroll bar. If hsbWidth.Value is 200, the width of

picProfile will be set to 200 pixels. Similarly, when the user scrolls the vertical scroll bar

(vsbHeight), the height of the PictureBox (picProfile) changes according to the current

value of the scroll bar. If vsbHeight.Value is 300, the height of picProfile will be set to 300

pixels. This functionality allows the user to dynamically resize the PictureBox by adjusting

the scroll bars, making it more interactive and customizable.

Computer Programming II Page 51 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Activity Sheet

1. Create a program with a variety of basic controls and implement functionality to showcase
how each control can be used in a real application.

Computer Programming II Page 52 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

CHAPTER 7
FUNCTIONS

A function is similar to a normal procedure but the main purpose of the function is to accept

a certain input and return a value, which is passed on to the main program to finish the execution.

There are two types of functions, the built-in functions (or internal functions) and the functions

created by the programmers. The general format of a function is:

The arguments are values that are passed on to the function.

Lesson 1: MsgBox() Function

The objective of MsgBox is to produce a pop-up message box and prompt the user to click

on a command button before he /she can continues. The format is as follows:

The first argument, Prompt, displays the message in the message box. The Style Value

determines the type of command buttons appear on the message box, as shown in Table below.

The Title argument will display the title of the message board.

STYLE
NAME CONSTANT BUTTONS DISPLAYED
VALUE
0 vbOkOnly Ok button
1 vbOkCancel Ok and Cancel buttons
2 vbAbortRetryIgnore Abort, Retry and Ignore buttons
3 vbYesNoCancel Yes, No and Cancel buttons
4 vbYesNo Yes and No buttons
5 vbRetryCancel Retry and Cancel buttons

We can use named constant in place of integers for the second argument to make the programs

more readable.

Computer Programming II Page 53 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

In fact, VB will automatically shows up a list of names constant where you can select one of them.

For example:

and

are the same.

Note: yourMsg is a variable that holds values that are returned by the MsgBox() function.

The type of buttons being clicked by the users determines the values. It has to be declared

as Integer data type in the procedure or in the general declaration section. The table below

shows the values, the corresponding named constant and buttons.

STYLE
NAME CONSTANT BUTTON CLICKED
VALUE
1 vbOk Ok button
2 vbCancel Cancel button
3 vbAbort Abort button
4 vbRetry Retry button
5 vbIgnore Ignore button
6 vbYes Yes button
7 vbNo No button

To make the message box looks more sophisticated, you can add an icon besides the message.

There are four types of icons available in VB.NET as shown in Table below.

VALUE NAME CONSTANT ICON

16 vbCritical

32 vbQuestion

48 vbExclamation

64 vbInformation

Computer Programming II Page 54 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Example:

Computer Programming II Page 55 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Lesson 2: InputBox() Function

An InputBox( ) function allows the user to enter a value or a message in a text box. The

format is as follows:

userMsg is a variant data type but typically it is declared as string, which accepts the message

input by the user. The arguments are explained as follows:

 Prompt - The message displayed normally as a question asked.

 Title - The title of the Input Box.

 default-text - The default text that appears in the input field where the user may change

the message according to his or her wish.

 x-position and y-position - the position or the coordinates of the input box.

Example:

Computer Programming II Page 56 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Lesson 3: String Functions

The Mid Function

The Mid function is to retrieve a part of text from a given phrase. The format of the Mid

Function is:

where:

 phrase is the string from which a part of text is to be retrieved.

 position is the starting position of the phrase from which the retrieving process

begins.

 n is the number of characters to retrieve.

Example:

Computer Programming II Page 57 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

The Right Function

The Right function extracts the right portion of a phrase. The format is:

where n is the starting position from the right of the phase where the portion of the phrase

is to be extracted.

Example:

The Left Function

The Left function extracts the left portion of a phrase. The format is:

where n is the starting position from the left of the phase where the portion of the phrase

is to be extracted.

Computer Programming II Page 58 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Example:

The Trim Function

The Trim function trims the empty spaces on both side of the phrase. The format is:

For example:

The Ltrim Function

The Ltrim function trims the empty spaces of the left portion of the phrase. The format is:

For example:

Computer Programming II Page 59 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

The Rtrim Function

The Rtrim function trims the empty spaces of the right portion. The format is:

For example:

The InStr function

The InStr function looks for a phrase that is embedded within the original phrase and

returns the starting position of the embedded phrase. The format is:

Where n is the position where the Instr function will begin to look for the embedded phrase.

For example:

The function returns a numeric value.

The Ucase and the Lcase Functions

The Ucase function converts all the characters of a string to capital letters. On the other

hand, the Lcase function converts all the characters of a string to small letters.

The format is:

For example:

Computer Programming II Page 60 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

The Chr and the Asc functions

The Chr function returns the string that corresponds to an ASCII code while the

Asc function converts an ASCII character or symbol to the corresponding ASCII code.

ASCII stands for “American Standard Code for Information Interchange”. Altogether

there are 255 ASCII codes and as many ASCII characters. Some of the characters may

not be displayed as they may represent some actions such as the pressing of a key or

produce a beep sound.

The format of the Chr function is:

and the format of the Asc function is:

The following are some examples:

Lesson 4: Formatting Functions

The Format function is a very powerful formatting function that can display the numeric

values in various forms. A pre-defined format function is built into the software and does not need

to be created by a programmer. Pre-defined functions often exist to carry out common tasks, such

as: finding an average number or determining the length of a string. The format of the pre-defined

Format function is:

Where n is a number and the list of style arguments is given in the table below.

Computer Programming II Page 61 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

STYLE
DESCRIPTION EXAMPLE
ARGUMENT
General Displays the number without having Format(8972.234, “General
Number separators between thousands Number”)=8972.234
Displays the number without having
Format(8972.2,
Fixed separators between thousands and
“Fixed”)=8972.23
rounds it up to two decimal places.
Displays the number with separators or
Format(6648972.265,
Standard separators between thousands and
“Standard”)= 6,648,972.27
rounds it up to two decimal places.
Display the number with the dollar sign
in front has separators between Format(6648972.265,
Currency
thousands as well as rounding it up to “Currency”)= $6,648,972.27
two decimal places.
Converts the number to the percentage
Format(0.56324,
Percent form, displays a % sign, and rounds it up
“Percent”)=56.32%
to two decimal places.

Example:

Computer Programming II Page 62 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Formatting Using ToString Method

Other than using the Format function, VB.Net has introduced the ToString method to

format output. It is used together with the standard numeric format specifiers such as “c” which

stand for currency. Some of the most common numeric specifiers are listed in the table below:

FORMAT
DESCRIPTION EXAMPLES
SPECIFIER
- Displays a currency value. The
default is the US currency $ and in Dim myNum as Single =2011.123456
two decimal places.
- To display other currency, add a myNum.ToString("C")= $2011.12
culture code that specifies a country.
"C" For example, for Great Britain, you myNum.ToString("C4")= $2011.1234
add en-GB using the keyword
“CultureInfo.CreateSpecificCulture” myNum.ToString("C3", CultureInfo.
- Displays number of decimal digits by CreateSpecificCulture(”en-GB”))=
placing the digit after C, for example, £2011.123
C4 for decimal places.
Express a Number with in integer form
Dim myNumber As Integer = 2012.2344
"D" or "d" with specified number of digits. For
myNumber.ToString("D4")=2012
example, D4 means four-digit integer.
Express a number in exponential form
Dim myNumber As Double = 2012.2344
"E" or "e" with specified number of decimal
myNumber.ToString("e3")= 2.012e+003
places.
Mutiply a number by 100 and displayed Dim myNumber As Double = 0.23456
"P" or "p"
with a percentage symbol %. myNumber.ToString("P2")= 23.46%
Dim myNumber As Double=0.23456
"F" or "f" Specifies number of decimal points. myNumber.ToString(“F”)=0.23
myNumber.ToString(“F3”)=0.235

The ToString method together with the currency specifier “C” displays the output with the currency

sign $ and in two decimal places. The default currency is the currency used by your computer

system; in this case, it is the US currency. If you are not sure of what default currency your

computer uses, you can add the keyword “CultureInfo.CurrentCulture” to the ToString method as

shown in the example below:

Computer Programming II Page 63 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Activity Sheet

1. Develop a program that uses the MsgBox() function to display different types of message
boxes (e.g., information, warning, question) based on user interactions.

2. Write a program that prompts the user for input using the InputBox() function and
processes the input to perform a specific task.

3. Create a program that demonstrates various string functions (e.g., Length, Trim, Split) and
their usage for manipulating and analyzing strings.

4. Develop a program that uses formatting functions (e.g., Format(), ToString()) to display
numbers and dates in different formats.

Computer Programming II Page 64 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

CHAPTER 8
CONDITIONAL STATEMENTS

Decision making process is an important part of programming because it will help solve

practical problems intelligently so that it can provide useful output or feedback to the user. For

example, we can write a program that can ask the computer to perform certain task until a certain

condition is met, or a program that will reject non-numeric data. In order to control the program

flow and to make decisions, we need to use the conditional operators and the logical operators

together with the If Control Structure.

The Conditional Operators are powerful tools that can compare values and then decide

what actions to take, whether to execute a program or terminate the program and more. They are

also known as numerical comparison operators. Normally we use them to compare two values to

see whether they are equal or one value is greater or less than the other value. The comparison

will return true or false result. These operators are shown in table below.

OPERATORS MEANING
= Equal To
> Greater Than
< Less Than
>= Greater Than or Equal To
<= Less Than or Equal To
<> Not Equal To

Sometimes we might need to make more than one comparison before a decision can be

made and an action taken. In this case, using numerical comparison operators alone is not

sufficient, we need to use additional operators, and they are the logical operators. The logical

operators are shown in Table below.

OPERATORS MEANING
AND Both conditions must be True
OR One condition must be True
NOT Negates Truth

Computer Programming II Page 65 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Normally the above operators are used to compare numerical data. However, you can

also compare strings with the above operators. In making strings comparison, there are certain

rules to follows: Upper case letters are less than lowercase letters, "A"<"B"<"C"<"D"...<"Z" and

number are less than letters.

Lesson 1: If … Then

This is the simplest control structure which ask the computer to perform a certain

action specified by the VB expression if the condition is true. However, when the condition

is false, no action will be performed. The general format for the if...then... statement is:

Example:

Computer Programming II Page 66 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

This code snippet handles the FormClosing event of a form. When the form is about to close, it

displays a message box asking the user for confirmation. If the user chooses "No," the form

closing action is canceled.

This functionality is useful for preventing accidental closure of the application, giving the user a

chance to confirm their intention to exit.

Lesson 2: If … Then … Else

Using just If...Then statement is not very useful in programming and it does not provides

choices for the users. In order to provide a choice, we can use the If...Then...Else Statement. This

control structure will ask the computer to perform a certain action specified by the VB expression

if the condition is true. When the condition is false, an alternative action will be executed. The

general format for if...then... Else statement is:

Computer Programming II Page 67 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Example:

This code snippet handles the CheckedChanged event for a CheckBox (chkEULA). If the user

checks the CheckBox, the Button (btnSubmit) is enabled, allowing the user to proceed with

submission. Otherwise, if the user unchecks the checkbox, the btnSubmit button is disabled.

Lesson 3: Ladderized If’s

If there are more than two alternatives, using just If...Then...Else statement will not be

enough. In order to provide more choices, we can use the If...Then...ElseIf Statement or the

Ladderized If’s. The general format for the if...then... Else statement is:

Computer Programming II Page 68 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Example:

Computer Programming II Page 69 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

This code snippet handles the Click event of a button. When the button is clicked, it checks the

value entered. The If, ElseIf, and Else statements are used to check the value of the TextBox.

Depending on the value, the Label is set to the corresponding day of the week. However, if the

value is not between 1 and 7, a message box with the message "INVALID INPUT" is displayed.

Lesson 4: Nested If

A Nested If statement is a conditional statement used in programming to handle multiple

conditions. It involves placing one If statement inside another If statement. This allows the

program to evaluate multiple layers of conditions and execute the corresponding actions based

on whether the conditions are true or false. The general format for a Nested If statement is:

Computer Programming II Page 70 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

The nested If statement is particularly useful when more than two conditions need to be tested,

and the conditions depend on each other. This control structure enables the programmer to create

more complex decision-making processes.

Example:

The code snippet demonstrates the use of a nested If statement to evaluate eligibility for an

incentive based on user input. In the outer If Statement, it checks if the text in the ComboBox. If

the condition is true, it proceeds to the nested If statement. Otherwise, it displays a Message Box

stating that the user is not eligible for the incentive. Inside the outer If block, it checks the next

condition. If true, it displays a Message Box stating the user is eligible for the incentive. If false, a

Message Box indicating ineligibility will be displayed.

Computer Programming II Page 71 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

The revised code below utilizes Exit Sub to avoid duplicate Message Boxes for not being eligible.

After displaying the Message Box stating that the user is eligible for the incentive, it then exits the

subroutine using the Exit Sub. However, if one of the conditions are not met, it does not do

anything and proceeds to the next part of the code, the Message Box for ineligibility.

Alternatively, the Nested If can be converted into a simpler If Statement through the use of the

Logical Operators. The code below checks both conditions at the same time using the AND

operator. Using this operator, both the conditions must be met to display the Message Box for the

eligibility in the incentive.

Lesson 5: Select Case

The Select Case control structure is slightly different from the If...ElseIf control structure.

The difference is that the Select Case control structure basically only make decision on one

expression or dimension while the If...ElseIf statement control structure may evaluate only one

expression. Each If...ElseIf statement may also compute entirely different dimensions. Select

Computer Programming II Page 72 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Case is preferred when there exist many different conditions because using If...Then...ElseIf

statements might become too messy. The Select Case ...End Select control structure is:

Example:

Computer Programming II Page 73 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

This code snippet uses a Select Case statement to show the equivalent description of a value

entered in the TextBox. It compares the value of the expression against each Case condition in

the list. If the value does not match any of the specified cases, the Case Else block executes.

Here’s another example of using the Select Case Statement with range of values:

Computer Programming II Page 74 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Activity Sheet

1. Write a program that uses simple If … Then statements to make decisions based on user
input.

2. Create a program that uses If … Then … Else statements to handle multiple conditions
and provide different outputs based on those conditions.

3. Develop a program that demonstrates ladderized If statements for handling multiple


cases.

4. Write a program that uses nested If statements to handle complex conditions and
scenarios.

5. Create a program that uses the Select Case statement to manage multiple choices or
conditions that is more efficient than the ladderized If statements.

Computer Programming II Page 75 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

CHAPTER 9
LOOPING STATEMENTS

Visual Basic allows a procedure to repeat many times as long as the processor could

support. We call this looping. Looping is required when we need to process something repetitively

until a certain condition is met. For example, we can design a program that adds a series of

numbers until it exceed a certain value, or a program that asks the user to enter data repeatedly

until he or she keys in the word 'Finish'. In Visual Basic, we have three types of Loops, they are

the For...Next loop, the Do loop and the While...End While loop.

Lesson 1: For…Next Loop

The For...Next loop is a control flow statement for specifying iteration, which allows code

to be executed repeatedly. The loop iterates over a range of values, executing the statements

within the loop for each value in the range. The format is:

Example:

Computer Programming II Page 76 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

In the above example, the For...Next loop is used to iterate from 1 to 10. The For...Next loop in

operates by initializing a loop variable x to a starting value, in this case, 1. It then evaluates a

condition to check if the current value of x is less than or equal to an end value, here 10. If the

condition is true, the loop executes the statements within its body, concatenating the current value

of x to the lblOutput.Text property along with a space. After executing the loop body, the loop

variable x is incremented by the step value, which is 1. The condition is re-evaluated, and if x is

still less than or equal to 10, the loop runs again. This process continues until x exceeds 10, at

which point the loop terminates.

Sometimes the user might want to get out from the loop before the whole repetitive process is

completed. The command to use is Exit For. To exit a For….Next Loop, you can place the Exit

For statement within the loop; and it is normally used together with the If…..Then… statement.

Lesson 2: While…End While Loop

The While...End While loop in VB.NET repeatedly executes a block of code as long as a

specified condition remains true. Unlike the For...Next loop, this loop does not have a built-in

mechanism to automatically increment a counter variable, so any necessary changes to variables

that affect the loop's condition must be explicitly defined within the loop. The format is:

Computer Programming II Page 77 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Example:

In this example, the While...End While loop begins by initializing the value of x to 1, then evaluating

a condition. If the condition evaluates to True, the program enters the loop and executes the block

of statements inside it. After executing these statements, the loop returns to the beginning and

re-evaluates the condition. If the condition is still True, the loop runs the block of code again. This

cycle of checking the condition and executing the code continues until the condition evaluates to

False. Once the condition becomes False, the loop terminates. If we run the program, we will

have the same output in the For…Next loop.

Lesson 3: Do Loop

The structure of a Do Loop is very similar to the While….End While. However, there are

numerous variations in this kind of loop. Following are the different Do Loop formats:

Computer Programming II Page 78 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Example:

Computer Programming II Page 79 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

This program demonstrates four different Do loop formats: Do While, Do Loop While, Do Until,

and Do Loop Until. In the Do While loop, the condition is evaluated before the loop starts, and it

continues running as long as the condition is true. The Do Loop While loop, on the other hand,

executes its statements at least once before checking the condition at the end of the loop,

continuing if the condition is true. The Do Until loop evaluates the condition before the loop starts,

running until the condition becomes true. Conversely, the Do Loop Until loop executes its

statements at least once before checking the condition at the end, repeating until the condition is

true. All four loops in the program increment the variable x from 1 to 10, just like in the For and

While loop, but they differ in when they evaluate their respective conditions relative to the loop's

execution.

Computer Programming II Page 80 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Lesson 4: Nested Loop

Loops can be placed inside another loop, allowing for more complex iteration processes.

In a nested loop, the inner loop executes completely for each iteration of the outer loop. This

structure is useful for tasks that involve multiple dimensions, such as iterating through a two-

dimensional array or performing repeated actions within repeated actions. Nested loops can be

of the same type (e.g., a For loop inside another For loop) or different types (e.g., a While loop

inside a For loop), providing flexibility for various scenarios. However, it's important to manage

them carefully to avoid excessive computational complexity and ensure the logic is clear and

efficient.

Example:

In this program, two For loops are nested to create a multiplication table. The outer loop iterates

through the numbers 1 to 10, representing the multiplicands, while the inner loop iterates through

the numbers 1 to 10, representing the multipliers. For each combination of x (the multiplicand)

and y (the multiplier), the product x * y is calculated and attached with the contents of the TextBox,

followed by a Tab character for formatting. After the inner loop completes, a newline character

(vbCrLf) is added to the TextBox to move to the next line for the row of the multiplication table to

be properly formatted.

Computer Programming II Page 81 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

The program above can also be created using different loop formats just like the code below,

which demonstrates the same multiplication table using While and Do loop:

Computer Programming II Page 82 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Activity Sheet

1. Develop a program that uses a For…Next loop to perform repetitive tasks.

2. Write a program that uses a While…End While loop to perform actions until a specific
condition is met.

3. Create a program that uses a Do Loop to continuously perform an action until a condition
changes.

4. Implement a program that uses nested loops to perform tasks involving multiple levels of
repetition.

Computer Programming II Page 83 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

CHAPTER 10
ARRAYS

Lesson 1: Introduction to Arrays

By definition, an array is a list of variables with the same data type and name. When we

work with a single item, we only need to use one variable. However, if we have a list of items,

which are of similar type to deal with, we need to declare an array of variables instead of using a

variable for each item. For example, if we need to enter one hundred names, it is difficulty to

declare 100 different names; this is a waste of time and efforts. Therefore, instead of declaring

one hundred different variables, we need to declare only one array. We differentiate each item in

the array by using subscript, the index value of each item, for example name(0), name(1),name(2)

.......etc. , which will make declaring variables streamline and much systematic.

We can use Public or Dim statement to declare an array just as the way we declare a

single variable. The Public statement declares an array so that it can be used throughout the

entire application while the Dim statement declares an array that can be used only in a local

procedure.

Lesson 2: One-dimensional Array

An array can be one dimensional or multidimensional. One-dimensional array is like a list

of items or a table that consists of one row of items or one column of items. The table below

shows a one-dimensional array.

Student Name Name(0) Name(1) Name(2) Name(3) Name(4)

The general format to declare a one-dimensional array is as follow:

The argument subs indicate the last subscript in the array.

Computer Programming II Page 84 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Example 1.1:

declare an array that consists of 10 elements starting from CusName(0) to CusName(9).

Example 1.2:

The statement above declares an array that consists of the first element starting from

Count (100) and ends at Count (500)

Example 2: Creating a Name List

Computer Programming II Page 85 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

This program uses a one-dimensional array to store and display names entered by the user.

When the Button is clicked, the user is prompted to enter names into the array using an InputBox.

After all names are entered, each are assigned to specific indexes in the array as shown in the

table below:

Names(5) Names(0) Names(1) Names(2) Names(3) Names(4)

Index 0 1 2 3 4
Value Juan Pedro Maria Dan Chris

When the Button is clicked, the names stored in the array are displayed in the ListBox.

Lesson 3: Two-dimensional Array

A two-dimensional array in Visual Basic is like a table or a matrix with rows and columns.

It is useful for storing and manipulating data that naturally fits into a grid-like structure, such as a

spreadsheet or a game board. You can declare a two-dimensional array by specifying the number

of rows and columns it will have. The general format to declare a two dimensional array is:

The total number of elements will be (sub1+1)x(sub2+1). For example, Dim Score(2,3) will

produce an array that comprises 3x4=12 elements, as shown in table below:

Computer Programming II Page 86 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Score(0,0) Score(0,1) Score(0,2) Score(0,3)


Score(1,0) Score(1,1) Score(1,2) Score(1,3)
Score(2,0) Score(2,1) Score(2,2) Score(2,3)

Example: Managing Students’ Examination Scores

In this example, we want to key in the examination marks for five students and four subjects.

Since we are handling two variables here, i.e. name and subject, we declare a two dimensional

array (Scores (4,3). The first dimension represents student names and the second dimension

represents the subjects. Combining both produces the scores for each student for each subject.

Computer Programming II Page 87 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

For example, the score for the first student for the first subject will be score (0, 0). We let the user

enter the student names, subject titles as well as the scores. Then, we used two nested loops

involving the For...Next structure. The first loop gets the students’ names and the second loop

gets the students’ scores for the four subjects. To achieve the purpose, we introduced a one

dimensional array StudentName(4) to store the names of the five students. We also introduced a

one dimensional array Mark(3) to store the mark of every subject for every student .After entering

the name of the students and their scores, we get something like this:

StudentName(0) = Pedro Scores() = 89 Scores() = 90 Scores() = 95 Scores() = 93

StudentName(1) = Juan Scores() = 99 Scores() = 86 Scores() = 94 Scores() = 88

StudentName(2) = Maria Scores() = 80 Scores() = 93 Scores() = 98 Scores() = 84

StudentName(3) = Chris Scores() = 90 Scores() = 80 Scores() = 88 Scores() = 93

StudentName(4) = Dan Scores() = 85 Scores() = 88 Scores() = 82 Scores() = 89

Computer Programming II Page 88 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Activity Sheet

1. Develop a program that uses a one-dimensional array to store and manipulate a series of
related values.

2. Create a program that uses a two-dimensional array to represent and manipulate data in
a grid format.

Computer Programming II Page 89 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

CHAPTER 11
MENUS AND TOOLBAR

Menus and toolbars remain as the standard features of all windows applications despite

the development of more sophisticated GUI. The menu bar contains menus, which contain groups

of menu items that the user can used to execute certain commands to perform certain tasks like

opening a file, saving a file, printing a page, formatting a page and more. On the other hand, a

standard toolbar displays icons that can be used to open a file, save a file, viewing a document,

printing a document and more.

In this chapter, I will show you how to add Menus and icons to the toolbar of your

applications. We will use the text editor and execute the commands using the menus and the

toolbar icons. We shall also make this program more powerful by enabling it to format the text as

well as to print out the text from the text file. For this project, we will add MenuStrip1, ToolStrip1,

SaveFileDialog1, OpenFileDialog1, PrintDialog1 and FontDialog1 controls to the form.

Lesson 1: Adding Menus

First, drag the Menu Strip from the toolbox and position it at the top part of the form. Add

the first top-level menu by typing it in the textbox that appears with a blurred text “Type Here”.

The first menu you will add is File, but you type it with the ampersand sign in front, like this, &File.

The reason is the ampersand sign will underline the letter F, File at runtime so that the user can

use the keyboard short-cut keys to execute a command.

The second top-level menu that we shall add is Format, which we type it as &Format. The

next step is to add menu items to the File and the Format Menu. The three menu items that we

are going to add to the File menu are Open, Save, Print and Exit, type them as &Open, &Save,

&Print and E&xit. The menu items that we will add to the Format menu are Font (type it as Fo&nt),

Font Color (type it as Font &Color) and Background Color (type it as &Background Color). The

Computer Programming II Page 90 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

menu items can be moved upward or downward easily by dragging them. They can be deleted

easily by pressing the right mouse button and then click deleted in the pop-up dialog.

When we run the finished design, we shall see a window application that comprises menus

and menu items, as shown in Figure below. Notice the underlined characters of the menu items.

The menu item Open should execute a command that will allow the user to choose a file

from a storage source and open it via a pop-up dialog. The code is the same as the code to read

text file in the previous chapter. It involves the use of the OpenFileDialog control. Now, double

click on the Open menu item and enter the code as follows:

Computer Programming II Page 91 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Remember place the statement Imports System.IO before Public Class Form1 so that the

program is able to read the file. The open dialog is shown in Figure below.

Menu item Save executes command that writes file to the computer storage unit. The code is the

same as the code for writing file in the previous chapter. Click on the Save menu item and enter

the following code:

Computer Programming II Page 92 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Writing code for the Print command requires the use of the PrintDialog control. It comprises two

parts, the first part is to presents a print dialog for the user to set the options to print and second

part is to print the document. Click on the print menu item and enter the following codes:

 The code to presents a print dialog

 The code to print the document

Computer Programming II Page 93 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Still using the same file, we shall now add some toolbar items in form of icons. You can

look up for some free icons sites in Google to download the icons you intend to place on your

toolbar. To add icon to the menu, right click on the menu and choose properties window from the

dropdown list, then proceed to change the default image by clicking the three-dot button on the

right of the image property. Choose an icon or image file from your hard drive that you wish to

load as shown in the Figures below.

Computer Programming II Page 94 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Using the aforementioned method, the result is shown in Figure below

Lesson 2: Adding Toolbar Icons

First, add the ToolStrip from the toolbox to the form. To add items to the toolbar, click on

the small icon on the leftmost corner of the toolbar and choose Button from the dropdown list, as

shown in Figure below.

Computer Programming II Page 95 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Using the same method in the MenuStrip, configure the toolbar item and set their Image or Icon

properties as well as the ToolTipText to “Save File”. The ToolTipText is to display text when the

user places his or her mouse over the toolbar icon as shown in the figure below. The purpose is

to provide information about the action that can be executed by clicking the icon.

Next, we shall include all commands that we have in our MenuStrip and write code for every item

on the tool bar. Additional codes for the other button are provided below:

 Format Font Style

Computer Programming II Page 96 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

 Font Color

 Background Color

Computer Programming II Page 97 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Activity Sheet

1. Design a form with a menu strip and add various menu items to it. Implement functionality
for each menu item to demonstrate how menus can be used in an application.

2. Create a form with a toolbar and add icons for common actions. Implement event handlers
to perform actions when toolbar buttons are clicked.

Computer Programming II Page 98 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

CHAPTER 12
WORKING WITH DATABASE

Applications communicate with a database, firstly, to retrieve the data stored there and

present it in a user-friendly way, and secondly, to update the database by inserting, modifying

and deleting data. Microsoft ActiveX Data Objects.Net ADO.Net is a model, a part of the .Net

framework that is used by the .Net applications for retrieving, accessing and updating data.

Lesson 1: ADO.Net Object Model

ADO.Net object model is nothing but the structured process flow through various

components. The object model can be pictorially described as:

The data residing in a data store or database is retrieved through the data provider.

Various components of the data provider retrieve data for the application and update data. An

application accesses data either through a dataset or a data reader.

 Datasets store data in a disconnected cache and the application retrieves data from it.

 Data readers provide data to the application in a read-only and forward-only mode.

Computer Programming II Page 99 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Lesson 2: Data Provider

A data provider is used for connecting to a database, executing commands and retrieving

data, storing it in a dataset, reading the retrieved data and updating the database. The data

provider in ADO.Net consists of the following four objects:

1) Connection. This component is used to set up a connection with a data source.

2) Command. A command is a SQL statement or a stored procedure used to retrieve, insert,

delete or modify data in a data source.

3) DataReader. Data reader is used to retrieve data from a data source in a read-only and

forward-only mode.

4) DataAdapter. This is integral to the working of ADO.Net since data is transferred to and

from a database through a data adapter. It retrieves data from a database into a dataset

and updates the database. When changes are made to the dataset, the changes in the

database are actually done by the data adapter.

There are following different types of data providers included in ADO.Net:

 The .Net Framework data provider for SQL Server - provides access to Microsoft SQL

Server.

 The .Net Framework data provider for OLE DB - provides access to data sources exposed

by using OLE DB.

 The .Net Framework data provider for ODBC - provides access to data sources exposed

by ODBC.

 The .Net Framework data provider for Oracle - provides access to Oracle data source.

 The EntityClient provider - enables accessing data through Entity Data Model EDM

applications.

Computer Programming II Page 100 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Lesson 3: DataSet

DataSet is an in-memory representation of data. It is a disconnected, cached set of records

that are retrieved from a database. When a connection is established with the database, the data

adapter creates a dataset and stores data in it. After the data is retrieved and stored in a dataset,

the connection with the database is closed. This is called the 'disconnected architecture'. The

dataset works as a virtual database containing tables, rows, and columns. The following diagram

shows the dataset object model:

The DataSet class is present in the System.Data namespace. The following table describes all

the components of DataSet:

 DataTableCollection. It contains all the tables retrieved from the data source.

 DataRelationCollection. It contains relationships and the links between tables in a data

set.

Computer Programming II Page 101 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

 ExtendedProperties. It contains additional information, like the SQL statement for

retrieving data, time of retrieval, etc.

 DataTable. It represents a table in the DataTableCollection of a dataset. It consists of the

DataRow and DataColumn objects. The DataTable objects are case-sensitive.

 DataRelation. It represents a relationship in the DataRelationshipCollection of the

dataset. It is used to relate two DataTable objects to each other through the DataColumn

objects.

 DataRowCollection. It contains all the rows in a DataTable.

 DataView. It represents a fixed customized view of a DataTable for sorting, filtering,

searching, editing and navigation.

 PrimaryKey. It represents the column that uniquely identifies a row in a DataTable.

 DataRow. It represents a row in the DataTable. The DataRow object and its properties

and methods are used to retrieve, evaluate, insert, delete, and update values in the

DataTable. The NewRow method is used to create a new row and the Add method adds

a row to the table.

 DataColumnCollection It represents all the columns in a DataTable.

 DataColumn. It consists of the number of columns that comprise a DataTable.

Lesson 4: Connecting to a Database

A. Establishing the Database Connection

The first step in database operations is establishing a connection. In this

application, the OleDb.OleDbConnection class is used to create a connection to the

Access database. The connection string specifies the database provider

Computer Programming II Page 102 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

(microsoft.jet.oledb.4.0) and the path to the database file (dbPOS.mdb), which is

located in the application's startup path.

Here, dbCON is the connection object, and Open() is called to initiate the connection,

allowing the application to interact with the database.

B. Displaying Records

After establishing the connection, records are displayed using the

Display_Records method. This method involves setting up a DataSet and a

DataAdapter. The DataAdapter uses an SQL SELECT statement to retrieve all records

from the tblINVENTORY table and fills the DataSet. The data is then bound to a data grid

view (dgRecords) for user interaction.

Computer Programming II Page 103 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

This method not only displays the records but also updates text boxes with the first

record's data, providing a detailed view of the current record.

C. Navigating Through Records

The application includes navigation buttons that allow users to move through

records in the dataset. The RecPointer variable keeps track of the current record index.

The btnMF, btnMP, btnMN, and btnML correspond to buttons for moving to the first,

previous, next, and last records, respectively.

Computer Programming II Page 104 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

These methods call Display_Records() to update the display based on the new

RecPointer value. If we run the program, we will have the sample output as shown below.

Computer Programming II Page 105 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Lesson 5: Storing, Retrieving, and Manipulating Records

Here, we will delve into the core functionalities of managing inventory records within the

vb.net program. We will cover essential operations such as adding new records, editing existing

ones, searching for specific entries, and deleting records from the database. These actions are

facilitated through a set of menus, as illustrated in the figure below.

A. Adding New Records

To add a new record, we will be using the "Add" button (mnuAdd). This button

unlocks the text boxes for data entry and prepares the interface for inputting a new record.

The text boxes are cleared to prevent any existing data from being overwritten, and the

mnuSave button's text is changed to "Save" to indicate that the data will be saved as new

record into the database.

Computer Programming II Page 106 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

The Unlock_Textboxes method enables the text boxes for user input, and

Clear_Textboxes ensures that the text boxes are empty, preparing the form for new data

entry. The entered data is inserted into the database using an INSERT INTO SQL

command.

B. Updating Records

To modify an existing record, the user needs to select the record and click the

"Edit" button (mnuEdit). This will unlock the text boxes for editing and sets the mnuSave

button's text to "Update," indicating that changes will be saved to the existing record.

The PCode variable stores the current product code for reference. This ensures that the

correct record will be updated in the database. After making the necessary changes, the

Computer Programming II Page 107 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

program uses an UPDATE SQL command to modify the existing record in the database,

based on the value of the Primary Key which is the PCode.

C. Searching Records

This features a search function that enables users to quickly locate specific records

by entering criteria such as a product code or name. This function uses a SQL SELECT

statement with a WHERE clause to filter records based on the input.

Computer Programming II Page 108 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

The LIKE operator allows partial matches, making the search flexible. If records are found,

they are displayed. Otherwise, a message box informs the user, and the database

connection is reset.

D. Deleting Records

To remove a record, the user selects it and clicks the "Delete" button (mnuDelete).

The application confirms the deletion action to prevent accidental data loss. If confirmed,

it executes a DELETE FROM SQL command to remove the record from the database.

Deleting records is necessary for removing outdated, incorrect, or unnecessary entries

from the database. However, it must be used cautiously, as deleted records cannot be

recovered and may result in permanent data loss.

These four fundamental database operations (ADD, EDIT, SEARCH, and DELETE), also

known as CRUD (Create, Read, Update, Delete), describe the basic and core operations of

database management. They form the foundation upon which all other database manipulations

and interactions are built.

Computer Programming II Page 109 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Additional Methods

 Lock_Textboxes. This method is used to disable text boxes, preventing users from

modifying data unless explicitly allowed (e.g., during add or edit operations).

 Unlock_Textboxes. This method enables text boxes for data entry or editing, ensuring

that users can interact with the form only when appropriate.

 Clear_Textboxes. This method clears the contents of all text boxes, used primarily when

preparing the form for adding a new record.

Computer Programming II Page 110 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Activity Sheet

1. Develop a complete application that connects to a MS Access database and performs


basic operations of manipulating records in a database.

Computer Programming II Page 111 of 112


Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

References

Du, P. O. J. (2019). Visual Studio 2019 in depth: Discover and make use of the powerful
features of the Visual Studio 2019 IDE to develop better and faster mobile, web, and
desktop applications. BPB Publications.

Kiong, L. V. (2012). Visual Basic 2010 made easy. CreateSpace.

Microsoft. (n.d.). Visual Basic documentation. Retrieved from https://learn.microsoft.com/en-


us/dotnet/visual-basic/

Tutorials Point. (2015). VB.Net tutorial. Retrieved from


https://www.tutorialspoint.com/vb.net/index.htm

Zak, D. (2022). Programming with Microsoft Visual Basic 2019/2022. Course Technology.

Additional Resources (Video Tutorials)

https://youtube.com/playlist?list=PLRfBNGC4M6otChZ0dokEZsO9fnXTCp86r&si=nW12EztIKfb_AL6Y

Computer Programming II Page 112 of 112

You might also like