0% found this document useful (0 votes)
10 views70 pages

Prog2 Module Midterm

The document serves as an introductory guide to Visual Basic.Net, detailing its evolution, features, and the Integrated Development Environment (IDE) of Visual Studio. It covers fundamental concepts such as Object-Oriented Programming, interface design, control properties, event-driven programming, and data types. Additionally, it explains variable declaration, assignment, and constants, providing a foundation for programming in Visual Basic.Net.

Uploaded by

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

Prog2 Module Midterm

The document serves as an introductory guide to Visual Basic.Net, detailing its evolution, features, and the Integrated Development Environment (IDE) of Visual Studio. It covers fundamental concepts such as Object-Oriented Programming, interface design, control properties, event-driven programming, and data types. Additionally, it explains variable declaration, assignment, and constants, providing a foundation for programming in Visual Basic.Net.

Uploaded by

archiemelanio1
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

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 [Link] 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.

Microsoft launched the first graphical BASIC, Visual Basic Version 1 in 1991.

It is GUI based and especially developed for MS window.

Visual [Link] is a full-fledged Object-Oriented Programming (OOP)

Language; it has caught up with other OOP languages such as C++, Java, C# and

others

Page 1 of 70
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.

Page 2 of 70
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.

Page 3 of 70
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.

Page 4 of 70
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 [Link] 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 [Link] Programming

The main difference between [Link] 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.

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

allows the structure and methods in one class to be passed down the

hierarchy.

 Polymorphism. Object-oriented programming allows procedures

about objects to be created whose exact type is not known until runtime.

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

 [Link] allows users to write programs that break down into

modules. These modules represent the real-world objects; we also call

them classes or types.

Page 6 of 70
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 [Link] 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.

The Visual Basic Control Toolbox consists of all

the controls essential for developing a VISUAL [Link]

application. Controls in [Link] 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.

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

Lesson 2: Setting Control Properties in Properties Window

Page 8 of 70
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)

Page 9 of 70
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 [Link]” 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. [Link] 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 [Link] (RGB code). Now, click on the

form to go into the code

Page 10 of 70
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

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.

Page 11 of 70
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.

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:

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

CHAPTER 4
MANAGING [Link] DATA

Lesson 1: Data Types

Numeric Data Types

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

compute them mathematically. 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).

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

Non-numeric Data Types

sNonnumeric 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 0 to 2 billion characters
bytes
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 [Link] 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

Page 14 of 70
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 [Link], 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 [Link]
ThisDate 1NewDate
Long_Name_Can_beUSE His&Her

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

Declaring Variables

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

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:

Dim VariableName as String * n,

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

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

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

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:

Lesson 3: Constants

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

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:

Page 20 of 70
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 [Link], 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 [Link] to carry out arithmetic calculations, we need to write

code that involves the use of various arithmetic operators. The [Link] 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

[Link] 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.


Page 21 of 70
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:

Page 22 of 70
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:

Page 23 of 70
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. [Link] 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:

Page 24 of 70
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 [Link]. In [Link], 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

[Link]. 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:

[Link]("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:

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

CHAPTER 6
[Link] - 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

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

controls and restrictions applied to them.

Page 27 of 70
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:

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

Here, Handles [Link] 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

[Link] 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 [Link] 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.
ScrollBar It Implements the basic functionality of a scroll bar control.

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

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

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

two (2) event handlers for Button:

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

 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

Page 31 of 70
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.

Page 32 of 70
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.

Page 33 of 70
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([Link], "dddd, MMMM dd, yyyy") - This function formats the

date selected in the DateTimePicker ([Link]) 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.

Page 34 of 70
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.

 [Link]. This property gets the start date

of the selected range in the MonthCalendar.

 [Link]. 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 [Link] controls like the Timer runs in the

background. As shown in the figure below, the Timer control appears in the
Page 35 of 70
Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

bottom of the Visual Studio IDE.

Page 36 of 70
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.

 [Link]. This property gets the current date and time.

 Format([Link]). 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

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

One (1) second.

Page 38 of 70
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.

 [Link]. This property sets the system date. It

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

 [Link]. This property sets the system time. It

takes a string representing the time.

 Format([Link], "MM/dd/yyyy"). This function formats the value of

the DateTimePicker ([Link]) to the required date format

"MM/dd/yyyy".

 [Link]. 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.

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

PictureBox and ScrollBars

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

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,

Page 41 of 70
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

[Link] 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 [Link] is 300, the height of picProfile will be set to 300
Page 42 of 70
Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

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

by adjusting the scroll bars, making it more interactive and customizable.

Page 43 of 70
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

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

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

the programs more readable.

Page 45 of 70
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
VALUE NAME CONSTANT BUTTON CLICKED
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 [Link] as shown in Table below.

VALUE NAME CONSTANT ICON

16 vbCritical

32 vbQuestion

48 vbExclamation

64 vbInformation

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

Example:

Page 47 of 70
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:

Page 48 of 70
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:

Page 49 of 70
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.

Page 50 of 70
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:

Page 51 of 70
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:

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

The Chr and the Asc functions

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

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.

STYLE
DESCRIPTION EXAMPLE
ARGUMENT
Page 54 of 70
Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

Gener Displays the number without Format(8972.234,


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

Example:

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

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

are not sure of what default currency your computer uses, you can add the keyword

“[Link]” to the ToString method as shown in the example

below:

Page 57 of 70
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
Page 58 of 70
Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY

OR One condition must be True


NOT Negates Truth

Page 59 of 70
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:

Page 60 of 70
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:

Page 61 of 70
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:

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

Example:

Page 63 of 70
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:

The nested If statement is particularly useful


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

when more than two conditions need to be

tested, and the

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

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.

Page 66 of 70
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

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

also compute entirely different dimensions. Select

Page 68 of 70
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:

Page 69 of 70
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:

Page 70 of 70

You might also like