0% found this document useful (0 votes)
413 views

CompilationLecLab VB 2010 .NET JRU

The document provides an overview of Visual Basic 2010, including a brief history and description of Visual Basic. It discusses the Visual Basic integrated development environment and describes the main panes and windows, including the toolbox, solution explorer, properties window, and form designer. It also lists and describes some of the most commonly used toolbox objects in Visual Basic like buttons, textboxes, labels, and scrollbars.

Uploaded by

El Yang
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
413 views

CompilationLecLab VB 2010 .NET JRU

The document provides an overview of Visual Basic 2010, including a brief history and description of Visual Basic. It discusses the Visual Basic integrated development environment and describes the main panes and windows, including the toolbox, solution explorer, properties window, and form designer. It also lists and describes some of the most commonly used toolbox objects in Visual Basic like buttons, textboxes, labels, and scrollbars.

Uploaded by

El Yang
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 116

JOSE RIZAL UNIVERSITY

Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Introduction to Visual Basic 2010

A Brief Description of Visual Basic 2010


Visual Basic 2010 is the latest version of Visual Basic launched by Microsoft in 2010. It
is almost similar to Visual Basic 2008 but it 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, Visual Basic
2005, Visual Basic 2008 and the latest Visual Basic 2010. Visual Basic 2010 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 VB2010. In fact, if you are familiar with Visual Basic 6, you can learn
VB2010 effortlessly because the syntax and interface are almost similar. Visual Basic
2010 Express Edition is available for free download from the Microsoft site as shown
below:
http://www.microsoft.com/visualstudio/en-us/products/2010-editions/express

Visual Basic .NET (VB.NET)


Is an object-oriented computer programming language that can be viewed as an evolution
of Microsoft's Visual Basic (VB) which is implemented on the Microsoft .NET Framework.
Microsoft currently supplies Visual Basic free of charge.

Microsoft .NET Framework


Is a software framework that can be installed on computers running Microsoft Windows
operating systems

Compiled by: Mr. Roel C. Traballo 1


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Navigating the Visual Basic 2010 Integrated Development Environment

The Start Page


When you launch Visual Basic 2010 Express, you can see the start page of the
Integrated Development Environment, as shown in the figure below:

The IDE consists of a few panes, namely:


The Recent Projects Pane- it shows the list of projects that you have created recently.
The Get Started Pane- It provides some helpful tips so that you can quickly develop
your new application.
The Latest News pane- It provides latest online news about Visual Basic 2010
Express. It will announce new releases and updates. Besides that, it also shows two
icons, New Project and Open Project.

Compiled by: Mr. Roel C. Traballo 2


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

The New Project Dialog


When you click on the New Project icon, the Visual Basic 2010 New Project dialog
will appear, as shown in the figure.

The dialog box offers you five types of projects that you can create. They are
Windows Form Application
WPF Application
Console Application
Class Library and WPF
Browser Application.

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


Forms Application. At the bottom of this dialog box, you can change the default project name
WindowsApplication1 to some other name you like, for example, MyFirstApplication. After
you have renamed the project, click OK to go into the Designer interface.

Compiled by: Mr. Roel C. Traballo 3


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

The Visual Basic 2010 Screen Display

Solution
Explorer
Window

Form
Designer
Window

Properties
Window

Toolbox
Window

Form: The Form is the first place to build your application. It is the place to design the
user interface.

Close Button

Maximize Button

Minimize Button

Form Title

Control Menu

Form Designer

Compiled by: Mr. Roel C. Traballo 4


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

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

Properties
Project Name
Show All Files
Form Name
Refresh

View Code

View Designer

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

Properties Window

Object Box

Property Pages

Events

Properties

Alphabetical

Categorized
Propeties List

Setting Box

Compiled by: Mr. Roel C. Traballo 5


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Most Commonly used Toolbox Objects and Descriptions


Tool Name Purpose
Pointer Allows you to move and size forms and controls
Label Displays text that the user cannot edit during run time.
LinkLabel Adds a Web style link to a Windows Forms application
Button Displays a standard button that the user can click to perform actions
TextBox Accepts and displays text that the user can edit during run time.
MenuStrip Displays a menu while an application is running
CheckBox Displays a box that indicates whether an option is selected or deselected
RadioButton Displays a button that indicates whether an option is selected or deselected.
GroupBox Provides a visual and functional container for controls; similar to the Panel control,
but can display a caption but no scroll bars.
PictureBox Displays graphics in bitmap, GIF, JPEG, metafile, or icon format.
Panel Provides a visual and functional container for controls; similar to the GroupBox
control, but can display scroll bars but no caption
DataGrid Displays data in a series of rows and column
ListBox Displays a list from which a user can select one or more items.
CheckedListBox Displays a scrollable list of items, each accompanied by a check box
ComboBox Displays a drop-down list of items
ListView Displays items in one of four views (text only, text with small icons, text with large
icons, or report view.
TreeView Displays a hierarchy of nodes that can be expanded or collapsed.
TabControl Displays multiple tabs.
DateTimePicker Allows the user to select a single item from a list of dates or times.
MonthCalendar Displays an intuitive graphical interface for users to view and set date information
HScrollBar Displays a horizontal scroll bar
VScrollBar Displays a vertical scroll bar
Timer Performs actions at specified time intervals

Designing the Interface


Learning how to Design the Interface
Adding controls to the forms
Setting Control Properties

Compiled by: Mr. Roel C. Traballo 6


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Adding Controls to the Form


The first step in creating a new VB2010 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, as shown in figures below:

Compiled by: Mr. Roel C. Traballo 7


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Compiled by: Mr. Roel C. Traballo 8


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

The Visual Basic 2010 Control Toolbox consists of all the controls essential for
developing a VISUAL BASIC 2010 application. Controls in VB2010 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.

Setting the Control Properties Using 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, as shown in the figure.
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.

Compiled by: Mr. Roel C. Traballo 9


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Working with some controls (objects) and their properties:


Prefix Property Name Example
Form frm frmFormName frmSample
Label lbl lblLabelName lblSample
TextBox txt txtTextboxName txtSample
Button btn btnButtonName btnSample

Note:
Change only those object property names if it is needed in your program codes.
Changing object property name is a good practice in developing a Visual Basic .NET application

Compiled by: Mr. Roel C. Traballo 10


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Name : _______________________ Date Finished: ________ Rating:


Course/Section: _________ Time: ________
Instructor : _______________________

PRACTICE EXERCISE #1:

Sample Interface/Form layout: Edited Form:

Changing the properties of some controls/objects

Objects/Controls Name Text Event/Procedure


Form1 frmSample Sample Application Load
Label1 Label1 Enter your name: None
Label2 lblWelcome Welcome to Visual Basic .NET None
TextBox1 txtName None None
Button1 btnClick Click Click

Sample Output:

Writing Codes to your Form (Sample Application)


Double click the <Click> button
Type the code below:
o btnClick_Click procedure/event
Double click the <Form>
Type the code below:
o frmSample_Load procedure/event

To run the application:


Press <F5> function key OR
Click <Start> button

Compiled by: Mr. Roel C. Traballo 11


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Public Class frmSample


Inherits System.Windows.Forms.Form

Private Sub btnClick_Click(ByVal sender As System.Object, ByVal e


As System.EventArgs) Handles btnClick.Click
lblWelcome.Text = "Welcome! " & txtName.Text
End Sub

Private Sub frmSample_Load(ByVal sender As System.Object, ByVal e


As System.EventArgs) Handles MyBase.Load
txtName.Text = "Richard Gwapo"
End Sub
End Class

CODE WINDOW

Source Codes

Class Name Method Name

Notes:
In writing program codes / event procedure codes you can click the <View Code> button
under Solution Explorer window.
All procedure/event procedure will be generated between the Public Class and End Class
keyword.
Select the class name and the method name.
Procedure/Event Procedure name will depend on defined object property name.
Object Procedure/Event Procedure name and argument lists will be automatically
displayed once the object is being selected for code/program implementation.
Type the line of statement(s) between the Private Sub and End Sub keyword
o Single statement per line.
o Use underscore ( _ ) to continue on the next line.

Compiled by: Mr. Roel C. Traballo 12


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Use single quotation symbol ( ) if you wish to include comments.


Use & or + symbol to concatenate string values.
Visual Basic .NET codes use color coding:
o Green for comments
o Blue for keywords / reserved words
o Black for property name, string, variables & etc.
Code with underline (color blue underline) means wrong:
o object name
o usage of property
o undefined variable
o etc.
Switching from Code Window to Form Window OR vice versa click <View Code>
button and <View Designer> button under Solution Explorer Window
During run time you can go back to your form window by closing the running application
(click <Close> button) OR click <Stop Debugging> button
Try to use other object property for some enhancements of your form.
In changing object property be sure to select the desired object before applying any
properties attached to that object. (Click once the object)

Compiled by: Mr. Roel C. Traballo 13


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Adding New Form


Right Click on PracticeExercises project in the Solution Explorer

Click <Add>, the select either <New Item> or <Windows Form>

Select <Windows Form> then click <Add button>


o Note: you may also change the filename or you may accept the default name, i.e.,
Form2.vb as show in the Name box
o New form (Form2) has been added to your project.

Compiled by: Mr. Roel C. Traballo 14


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

How to run/execute Form 2


Double Click My Project in the Solution Explorer window
Change Startup form: click the drop-down button and choose Form2

Press <F5>function key OR Start Debugging (F5) button from the Main Window

Compiled by: Mr. Roel C. Traballo 15


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Name : _______________________ Date Finished: ________ Rating:


Course/Section: _________ Time: ________
Instructor : _______________________

PRACTICE EXERCISE #2:

Use the same Solution and Project and add new form (Form2) to your project:

Sample Interface / Form Layout:

Instructions:
Add five labels objects/controls to your form
Change the object name:
o lblRed
o lblYellow
o lblGreen
o lblBlue
o lblOrange
Type the codes below using the MouseMove
Method for each object.

Public Class Form1


Private Sub lblRed_MouseMove(ByVal sender As Object, ByVal e As
System.Windows.Forms.MouseEventArgs) Handles lblRed.MouseMove
Me.BackColor = Color.Red
End Sub

Private Sub lblBlue_MouseMove(ByVal sender As Object, ByVal e As


System.Windows.Forms.MouseEventArgs) Handles lblBlue.MouseMove
Me.BackColor = Color.Blue
End Sub

Private Sub lblGreen_MouseMove(ByVal sender As Object, ByVal e As


System.Windows.Forms.MouseEventArgs) Handles lblGreen.MouseMove
Me.BackColor = Color.Green
End Sub

Private Sub lblYellow_MouseMove(ByVal sender As Object, ByVal e As


System.Windows.Forms.MouseEventArgs) Handles lblYellow.MouseMove
Me.BackColor = Color.Yellow
End Sub
Compiled by: Mr. Roel C. Traballo 16
JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Private Sub lblOrange_MouseMove(ByVal sender As Object, ByVal e As


System.Windows.Forms.MouseEventArgs) Handles lblOrange.MouseMove
Me.BackColor = Color.Orange
End Sub

Private Sub Form1_MouseMove(ByVal sender As Object, ByVal e As


System.Windows.Forms.MouseEventArgs) Handles Me.MouseMove
Me.BackColor = Color.White
End Sub

End Class

Compiled by: Mr. Roel C. Traballo 17


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Name : _______________________ Date Finished: ________ Rating:


Course/Section: _________ Time: ________
Instructor : _______________________

GRADED EXERCISE #1:

FORM 1: Sample Interface/Form Layout:

Instructions:
Add 8 Buttons with 1 TextBox
The Buttons: Red, Green, Blue & Yellow is for TextBox text color (ForeColor)
o Once clicked will change the color of the text
The Buttons: Black, Cyan, Violet & White is for Form background color (BackColor)
o Once clicked will change the forms background color

Compiled by: Mr. Roel C. Traballo 18


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

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 VB2010, 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 VB2010 to carry out arithmetic calculations, we need to write code that
involves the use of various arithmetic operators.
The VB2010 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 VB2010 arithmetic operators are shown in table below
In order to compute inputs from users and to generate results, we need to use various
mathematical operators. In Visual Basic, except for + and -, the symbols for the operators
are different from normal mathematical operators.

Arithmetic Operators:
Operator Mathematical function Example
^ Exponential 2 ^ 4 = 16
* Multiplication 4 * 3 = 12
/ Division 12 / 4 = 3
Mod Modulus(return the remainder 15 Mod 4 = 3
from an integer division)
\ Integer Division(discards the 19 \ 4 = 4
decimal places)
+ Addition 7 + 7 = 14
Subtraction 30 8 = 22
Note: (+) plus can be used for addition & string concatenation
+ or & String concatenation "Visual "&"Basic"="Visual Basic"
"Visual "+"Basic"="Visual Basic"

Compiled by: Mr. Roel C. Traballo 19


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Name : _______________________ Date Finished: ________ Rating:


Course/Section: _________ Time: ________
Instructor : _______________________

PRACTICE EXERCISE #3:

In this example you need to insert two (2) TextBoxes, four (4) Labels and one (1) Button.
If Calculate button is clicked it will perform the four basic arithmetic operations and display the
results in four (4) Labels.

Public Class Form3

Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnCalculate.Click
Me.Label1.Text = Me.TextBox1.Text + Me.TextBox2.Text
Me.Label2.Text = Me.TextBox1.Text - Me.TextBox2.Text
Me.Label3.Text = Me.TextBox1.Text * Me.TextBox2.Text
Me.Label4.Text = Me.TextBox1.Text / Me.TextBox2.Text
End Sub

End Class

Compiled by: Mr. Roel C. Traballo 20


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

VAL Functions:
Like a method, a function is predefined procedure that performs a specific task.
However, unlike a method, a function returns a value after performing its task. The VAL
function temporarily converts a string to a number, and then returns the number.

Note: The number is stored in the computers memory only while the function is
processing

Syntax: VAL(string)

- Where string is the string you want treated as a number. Because Visual Basic
.NET must be able to interpret the string as numeric value, the string cannot include a
letter or a special character, such as a dollar sign, the comma, or the percent sing (%); it
can, however, include a period and a space. When Visual Basic .NET encounters an
invalid character in the Val functions string, Visual Basic .NET stops converting the
string to a number at that point.

Examples:

Val Function: Would be converted to:


Val(123) 123
Val(12,500) 12
Val(765Y) 765
Val($56.34) 0
Val(Abc) 0
Val( ) 0
Val(100%) 100
Val(12 500) 12500

Modified Calculate button source codes:


Me.Label1.Text = Val(Me.TextBox1.Text) + Me.TextBox2.Text
Or
Me.Label1.Text = Val(Me.TextBox1.Text) + Val(Me.TextBox2.Text)

Compiled by: Mr. Roel C. Traballo 21


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Format Function:
You can use the Format function to improve the appearance of the numbers displayed in
an interface.

Syntax: Format(expression, style)

- Expression specifies the number, date, time, or string whose appearance you
want to format.

- Style is either the name of a predefined Visual Basic .NET format style or, if you
want more control over the appearance of the expression, a string containing special
symbols that indicate how you want the expression displayed.

Number Format Style Description


Displays a number with dollar sign ($) and two decimal places; if
Currency appropriate, displays a number with a thousand separator, negative
numbers are enclosed in parenthesis
Displays a number with at least one digit to the left and two digits to
Fixed
the right of the decimal point
Displays a number with at least one digit to the left and two digits to
Standard the right of the decimal point; if appropriate, displays a number with
a thousand separators.
Multiplies a number by 100 and displays the number with a percent
Percent
sign (%); displays two digits to the right of the decimal point.
Displays number output but not required
# Example:
o Format(x,###) => Output: 123, 12, 1, none
Display number output and required
0 Example
o Format(x,000) => Output: 123, 456, 789, 012
Thousands separator & Decimal point separator
Example:
o Format(x,#.##) => Output: 1.23, 4.5, 6.,
, and . o Format(x,0.00) => Output: 1.23, 4.56, 7.89
o Format(x,0.##) => Output: 1.23, 4.5, 5.
o Format(x,#.00) => Output: 1.23, 4.56, .78
o Format(x,#,###.00) =>Output:1,234.56, 789.00

FormatNumber Function:
The FormatNumber function returns a formatted string representation for a number.

Syntax: FormatNumber(expression [, digits_after_decimal]


[, include_leading_zero]
[, use_parens_if_negative]
[, groups_digits] )

Compiled by: Mr. Roel C. Traballo 22


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Where:
expression - The numeric expression to format
digits_after_decimal - The number of digits to display after the decimal point
include_leading_zero - If the number is less than 1 and greater than -1, determines whether the
number should have a leading 0 before the decimal point.
use_parens_if_negative - Determines whether negative numbers are surrounded
with parentheses instead of using a minus sign.
groups_digits - Determines whether digits to the left of the decimal point are grouped with
thousands separators.

Examples:
Expression Result
FormatNumber(1.23456) 1.23
FormatNumber(1.23456, 3) 1.235
FormatNumber(0.123456, 2, TriState.False) .12
FormatNumber(0.123456, 2, TriState.True) 0.12
FormatNumber(-12345.12, , TriState.False) -12,345.12
FormatNumber(-12345.12, , TriState.True) (12,345.12)
FormatNumber(-12345.12, , TriState.True, TriState.False) (12345.12)

System Date and Time Functions:


The system date is the current date according to your computer systems clock.

Syntax: Today[.methodname] where methodname is optional

The system time is the current time according to your computer systems clock.

Syntax: TimeOfDay[.methodname] where methodname is optional

Note: For these examples, assume that the system date is 11/15/06 and the system time is
4:30:44 PM

Examples: System Date Results


Today 11/15/2006
Today.ToShortDateString 11/15/2006
Today.ToLongDateString Wednesday, November 15, 2006
Today.ToString(MMMM d) November 15
Today.Month 11
Today.DayOfWeek.ToString Wednesday

Examples: System Time Results


TimeOfDay 4:30:44 PM
TimeOfDay.ToLongTimeString 4:30:44 PM
TimeOfDay.ToShortTimeString 4:30 PM
TimeOfDay.ToString(hh tt) 4 PM
TimeOfDay.Hour 4

Compiled by: Mr. Roel C. Traballo 23


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Name : _______________________ Date Finished: ________ Rating:


Course/Section: _________ Time: ________
Instructor : _______________________

PRACTICE EXERCISE #4:

Use the same Solution and Project and add new form (Form3) to your project:

Sample Interface / Form Layout:

Sample Output:

Compiled by: Mr. Roel C. Traballo 24


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Instructions:
Add five Labels to your form
Use the default object name of each label (i.e.. Label1, Label2, Label3, Label4, Label5)
Change Labels properties:
o Label1, Label2, Label3 & Label5
Font: 14
o Label4
Font: 48
Add Timer object
Note: Timer object will be displayed on the form but at the lower part of the screen.
Change Timer properties:
o Enable: TRUE
o Interval: 1000
Double click Timer object and type the codes below:

Note: Your output will be based on the computer system date.

Date and Time Function (using Visual Basic 6.0)


Public Class frmDateTime

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles Timer1.Tick

Label1.Text = Format(Now, "dddd")


Label2.Text = Format(Now, "hh:mm:ss tt")
Label3.Text = Format(Now, "MMMM")
Label4.Text = Format(Now, "dd")
Label5.Text = Format(Now, "yyyy")
End Sub
End Class

Modified codes: Date and Time Function (using Visual Basic .NET)
Public Class frmDateTime

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles Timer1.Tick
'Label1.Text = Format(Now, "dddd")
Label1.Text = Today.DayOfWeek.ToString
'Label2.Text = Format(Now, "hh:mm:ss tt")
Label2.Text = TimeOfDay
'Label3.Text = Format(Now, "MMMM")
Label3.Text = Today.ToString("MMMM")
'Label4.Text = Format(Now, "dd")
Compiled by: Mr. Roel C. Traballo 25
JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Label4.Text = Today.ToString("dd")
'Label5.Text = Format(Now, "yyyy")
Label5.Text = Today.Year
End Sub
End Class

Compiled by: Mr. Roel C. Traballo 26


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Variables & Constants


Besides storing data in the properties controls, a programmer also can store data
temporarily, in memory locations inside the computer. The memory locations are called
variables, because the contents of the locations can change as the program is running.
It may be helpful to picture a variable as a small box inside the computer. You can enter
and store data in the box, but you cannot actually see the box.
A variable is use to hold information that is not stored in a control on the user interface.

Data Type
Each variable (memory location) used in an application must be assigned a data type by
the programmer. The data type determines the type of data the variable can store/hold.

Type Stores Memory required Values


Boolean Logical value 2 bytes True, False
Byte Binary number 1 byte 0 to 255 (unsigned)
Char One character 2 bytes One character
Date Date and Time information 8 bytes Returns date and time
Decimal Fixed-point number 16 bytes Large number values
Number with decimal
Double Floating-point number 8 bytes
places
Integer Integer 4 bytes Whole numbers
Long Integer 8 bytes Whole numbers
Object Object reference 4 bytes N/A
Short Integer 2 bytes -32,768 to 32,767
Number with decimal
Single Floating-point number 4 bytes
values
0 to approximately 2
String Text Varies
billion characters.

Rules for naming variables:


1. The name must begin with a letter.
2. The name must contain only letters, numbers, and the underscore character. No
punctuation characters or spaces are allowed in the name.
3. The name cannot contain more than 255 characters. (32 characters is the recommended
maximum number of characters to use)
4. The name cannot be a reserved word

Valid variable names Invalid variable names


blnPrint Print The name cannot be a reserved word
dec2006Sales 2002SalesDec The name must begin with a letter
intRegionWest intRegion West The name cannot contain a space
mstrFirstName mstrFirst.Name The name cannot contain punctuation

Compiled by: Mr. Roel C. Traballo 27


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Declaring a Variable
You use a declaration statement to declare, or create, a variable. The declaration
statement you enter in your code will follow the syntax:

accessibility variablename [As datatype][=initialvalue]

Accessibility - is typical either the keyword Dim or the keyword Private. The
appropriate keyword to use depends on whether the variable is a local (Dim) or form-level
(Private) variable.
Variablename is the variables name
Datatype is the variables data type
Initialvalue is the value you want stored in the variable when it is created in the
computers internal memory.

Example of variable declarations:

Statement and Explanation


Dim intHours As Integer

- Declares an integer variable named intHours; the variable is automatically initialized to 0


Dim sngRate As Single = 0.03

- Declares a Single variable named sngRate and initializes to 0.03


Dim decPrice, decDiscount as Decimal

- Declares two Decimal variables named decPrice and decDiscount; the variables are
automatically initialized to 0
Dim mblnDataOk as Boolean

- Declares a Boolean variable named mblnDataOk; the variable is automatically initialized to


False
Dim strName as String, intAge as Integer

- Declares a String variable named strName and an Integer variable named intAge; the string
variable is automatically initialized to Nothing, and the Integer variable is automatically
initialized to 0

Note: After a variable is created, you can use an assignment statement/operator to store other
data in the variable.

Assigning Data to an Existing Variable

Syntax: variable_name = value


Example: Dim intNumber as Integer
intNumber = 500
intNumber = intNumber * 2

Compiled by: Mr. Roel C. Traballo 28


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Declaring Constant values


Like a variable, a named constant a memory location inside the computer. However,
unlike a variable, the contents of a named constant cannot be changed while the program is
running.

Syntax: Const constantname [As datatype] = expression

- where constantname and datatype are the constants name and data type, respectively,
and expression is the value you want to assign to the named constant

Examples:
Const statement Explanation
Const conPi As Single = 3.1416 Creates a Single named constant named conPi and
assigns the literal constant 3.1416 to it.
Const conMsg As String = Creates a String named constant named conMsg and
Greate! assigns the literal constant Great! to it.
Const conPrice as Integer = 25 Creates an Integer named constant named conPrice and
assigns the literal constant 25 to it.

Modified codes Form3

Public Class Form3

Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnCalculate.Click
Dim number1, number2, sum, difference, product As Integer
Dim quotient As Single

number1 = Me.TextBox1.Text
number2 = Me.TextBox2.Text

sum = number1 + number2


difference = number1 - number2
product = number1 * number2
quotient = number1 / number2

Me.Label1.Text = sum
Me.Label2.Text = difference
Me.Label3.Text = product
Me.Label4.Text = FormatNumber(quotient)
End Sub
End Class

Compiled by: Mr. Roel C. Traballo 29


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Clear TextBoxes entries, Close button and Focus( ) method

Modified Codes

Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnClear.Click
'Me.TextBox1.Text = ""
'Me.TextBox2.Text = ""
Me.TextBox1.Clear()
Me.TextBox2.Clear()
Me.Label1.Text = ""
Me.Label2.Text = ""
Me.Label3.Text = ""
Me.Label4.Text = ""

Me.TextBox1.Focus()
End Sub

Private Sub btnClose_Click(ByVal sender As Object, ByVal e As System.EventArgs)


Handles btnClose.Click
Me.Close()
'End
End Sub

Compiled by: Mr. Roel C. Traballo 30


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Name : _______________________ Date Finished: ________ Rating:


Course/Section: _________ Time: ________
Instructor : _______________________

GRADED EXERCISE #2:

FORM 1: Sample Interface/Form Layout:

Note:
Make necessary procedure/event on the
following buttons:
o +, , *, /, MOD & \
Clear button will clear all textboxes
Close button will close the application

Name : _______________________ Date Finished: ________ Rating:


Course/Section: _________ Time: ________
Instructor : _______________________

FORM 2: Sample Interface/Form Layout:

Formula:

Semestral Grade = 25% of Prelim Grade


25% of Midterm Grade
50% of Final Grade

Note:
Remove the Minimize, Maximize & Close button
o In the properties window set:
ControlBox: FALSE
Set TextBox (Semestral Grade) to:
Enabled: FALSE

Compiled by: Mr. Roel C. Traballo 31


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Name : _______________________ Date Finished: ________ Rating:


Course/Section: _________ Time: ________
Instructor : _______________________

FORM 3: Sample Interface/Form Layout:

Form Name : MPFRM03<FirstLastName> Example: MPFRM03RichardGwapo

Make necessary procedure/event for the following buttons:


Calculate
Clear
Close

Compute for the following:


Sub-Total
Discount Amount = 20% of sub-total
Net Amount

Name : _______________________ Date Finished: ________ Rating:


Course/Section: _________ Time: ________
Instructor : _______________________

FORM 4: Sample Interface/Form Layout:

Formulas:
- Area
A=r2
- Circumference
C=2r
- Diameter
D=2r
Note:
Use Const keyword to define the
value of
= 3.1416
Limit decimal place to 2 only using
Format function

Compiled by: Mr. Roel C. Traballo 32


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

MsgBox Function and MessageBox.Show Method

MsgBox ( )
MsgBox is used to produce a pop-up message box and prompt the user to
click on a command button before you can continue.
Format
msgVariable = MsgBox(Prompt, Style Value, Title)

The msgVariable is any variable with Byte/Integer data type


The 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 xx.
The Title argument will display the title of the message board.

MsgBox Function
Style Value Named Constant Buttons Displayed
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. In fact, VB will automatically shows up a list of names constant where
you can select one of them.

For example,
yourMsg=MsgBox( "Click OK to Proceed", 1, "Startup Menu")
and
yourMsg=Msg("Click OK to Proceed". vbOkCancel,"Startup Menu")
are the same.

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.

Value Named 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

Compiled by: Mr. Roel C. Traballo 33


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

MessageBox.show( ) Method
MessageBox.Show method is used to display a message box that contains text, one or
more buttons, and an icon.

Format:
MessageBox.Show(text, caption, buttons, icon[,defaultButton])

Argument Meaning
Text Text to display in the message box
Caption Text to display in the title bar of the messagebox
Buttons Buttons to display in the message box; can be one of the following constants:
MessageBoxButtons.AbortRetryIgnore
MessageBoxButtons.OK
MessageBoxButtons.OKCancel
MessageBoxButtons.RetryCancel
MessageBoxButtons.YesNo
MessageBoxButtons.YesNoCancel
Icon Icon to display in the message box; typically, one of the following constants:
MessageBoxIcon.Exclamation
MessageBoxIcon.Information
MessageBoxIcon.Stop
MessageBoxIcon.Question
defaultButton Button automatically selected when the user presses Enter; can be one of the
following constants:
MessageBoxDefaultButton.Button1 (default setting)
MessageBoxDefaultButton.Button2
MessageBoxDefaultButton.Button3

Example #1: Displays an information message box that contains the message Record Deleted.

MessageBox.Show(Record deleted...,Payroll, MessageBoxButtons.OK, _


MessageBoxIcon.Information)

Message box with information icon and with OK button only

Compiled by: Mr. Roel C. Traballo 34


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Example #2: Displays a warning message box that contains the message Delete this record?

MessageBox.Show(Delete this record...,Payroll, MessageBoxButtons.YesNo, _


MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2)

Message box with Exclamation icon, with Yes and No buttons and with No as the default button

Example #3: Displays a question message box that contains the message Delete this record with Are
your sure printed below.

MessageBox.Show("Delete this record..." + vbNewLine + "Are you sure...", "Payroll", _


MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question)

Message box with question mark icon, with Yes, No and Cancel buttons

Example #3: Displays a stop message box that contains the message Unauthorized user keep out.

MessageBox.Show("Unauthorized user keep out...", "Payroll", MessageBoxButtons.OK,


MessageBoxIcon.Stop)

Message box with stop/error icon, with OK button

Note:
The underscore ( _ ) in the given message box statement means to continue the line of statement.
The vbNewLine constant is used to display/print the text/string on a separate line.

Compiled by: Mr. Roel C. Traballo 35


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

After displaying the message box, the MessageBox.Show method waits for the user to choose one
of the buttons displayed in the message box. It then closes the message box and returns a number
(an integer) that indicates which button the user choose.
Lists of associated with the various buttons. It also lists the constant values assigned to each
number, and the meaning of the numbers and constants.

Number Constant Meaning


1 DialogResult.OK User choose the OK button
2 DialogResult.Cancel User choose the Cancel button
3 DialogResult.Abort User choose the Abort button
4 DialogResult.Retry User choose the Retry button
5 DialogResult.Ignore User choose the Ignore button
6 DialogResult.Yes User choose the Yes button
7 DialogResult.No User choose the No button

Compiled by: Mr. Roel C. Traballo 36


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Name : _______________________ Date Finished: ________ Rating:


Course/Section: _________ Time: ________
Instructor : _______________________

PRACTICE EXERCISE #5:

Compiled by: Mr. Roel C. Traballo 37


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Public Class Form3

Private Sub btnMsgBox_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnMsgBox.Click
MsgBox("Hello World!")
MsgBox("Are you nice?", MsgBoxStyle.Question + MsgBoxStyle.YesNo, "Question")
End Sub

Private Sub btnMessageBox_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnMessageBox.Click
MessageBox.Show("Hello Philippines")
MessageBox.Show("Please compelte all entries", "Information",
MessageBoxButtons.OKCancel, MessageBoxIcon.Information)
End Sub

End Class

Compiled by: Mr. Roel C. Traballo 38


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

The IfThenElse Statement


The selection structure, also called decision structure is used when you want a program to
make a decision or comparison and then, based on the result of that decision or comparison;
select a particular set of tasks to perform.

Syntax: If condition Then


[ statement block containing one or more statements to be processed when
the condition is true. ]
Else
[ statement block containing one or more statements to be processed when
the condition is false. ]
EndIf

Example:

If Ans = DialogResult.Yes Then


MessageBox.Show(You clicked YES button)
Else
MessageBox.Show(You clicked NO button)
EndIf

Comparison Operators:
The comparison operator which is also referred to as relational operators lists the six most
commonly used comparison operators.

Operator Operations
= Equal to
> Greater than
>= Greater than or Equal to
< Less than
<= Less than or Equal to
<> Not equal to

Compiled by: Mr. Roel C. Traballo 39


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Logical Operators:
The logical operators, sometimes referred to as Boolean operators, allow you to combine
two or more conditions into one compound conditions

Operator Operations Precedence number


Reverses the value of the condition; True
Not 1
becomes False, and False becomes True
All condition must be true for the compound
And 2
condition to be true
Same as the And operator, except performs
AndAlso 2
short-circuit evaluation
Only one of the conditions must be true for the
Or 3
compound condition to be true
Same as the Or operator, excepts performs
OrElse 3
short-circuit evaluation
One and only one condition can be true for the
Xor 4
compound condition to be true

Truth Tables
The tables below summarize how Visual Basic .NET evaluates the logical operators in an
expression. Like expressions containing comparison operators, expression containing logical
operators always evaluate to a Boolean value.

Not Operator:
Condition Value/Result
True False
False True

And Operator:
Condition1 Condition2 Value/Result
True True True
True False False
False True False
False False False

AndAlso Operator:
Condition1 Condition2 Value/Result
True True True
True False False
False (not evaluated) False

Or Operator:
Condition1 Condition2 Value/Result
True True True
True False True
False True True
False False False

Compiled by: Mr. Roel C. Traballo 40


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

OrElse Operator:
Condition1 Condition2 Value/Result
True (not evaluated) True
False True True
False False False

Xor Operator:
Condition1 Condition2 Value/Result
True True False
True False True
False True True
False False False

Precedence of Operations:
Operator Operation Order
^ Exponentiation 1
Negation 2
*, / Multiplication and Division 3
\ Integer Division 4
Mod Modulo Division 5
+, Addition and Subtraction 6
& Concatenation 7
Equal to, greater than, greater than or Equal to,
=, >, >=, <, <=, <> 8
Less than, Less than or Equal to, Not equal to
Not Reverses truth value of condition 9
All conditions must be true for the compound
And, AndAlso 10
condition to be true
Only one condition needs to be true for the
Or, OrElse 11
compound condition to be true
One and only one condition can be true for the
Xor 12
compound condition to be true

Modified Codes Form3

Public Class Form3

Private Sub btnMsgBox_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnMsgBox.Click
Dim answer As Byte
MsgBox("Hello World!")
answer = MsgBox("Are you nice?", MsgBoxStyle.Question + MsgBoxStyle.YesNo,
"Question")
If answer = vbYes Then
MsgBox("Good")
Else
MsgBox("Bad")

Compiled by: Mr. Roel C. Traballo 41


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

End If
End Sub

Private Sub btnMessageBox_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnMessageBox.Click
Dim answer As Byte
MessageBox.Show("Hello Philippines")
answer = MessageBox.Show("Please complete all entries", "Information",
MessageBoxButtons.OKCancel, MessageBoxIcon.Information)
If answer = DialogResult.OK Then
MessageBox.Show("OK")
Else
MessageBox.Show("CANCEL")
End If
End Sub

End Class

Compiled by: Mr. Roel C. Traballo 42


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

The Select Case Statement


The format is :

Select Case expression


Case value1
Block of one or more VB statements
Case value2
Block of one or more VB Statements
Case value3
Block of one or more VB statements
Case value4
.
.
Case Else
Block of one or more VB Statements
End Select

Note:
The data type specified in expression must match that of Case values.

Example of Selective Structure 1


'Examination Grades
Dim grade As String
Private Sub Compute_Click( )
grade=txtgrade.Text

Select Case grade


Case "A"
result.Text="High Distinction"
Case "A-"
result.Text="Distinction"
Case "B"
result.Text="Credit"
Case "C"
result.Text="Pass"
Case Else
result.Text="Fail"
End Select
End sub

Note:
Please note that grade is a string, so all the case values such as "A" are of String data
type.

Compiled by: Mr. Roel C. Traballo 43


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Example of Selective Structure 2


Dim mark As Single
Private Sub Compute_Click()
'Examination Marks
mark = mrk.Text

Select Case mark


Case Is >= 85
comment.Text = "Excellence"
Case Is >= 70
comment.Text = "Good"
Case Is >= 60
comment.Text = "Above Average"
Case Is >= 50
comment.Text = "Average"
Case Else
comment.Text = "Need to work harder"
End Select
End Sub

Note
we use the keyword Is here to impose the conditions. This is generally used for numeric
data.

Example of Selective Structure 3


Dim mark As Single
Private Sub Compute_Click()
'Examination Marks
mark = mrk.Text

Select Case mark


Case 0 to 49
comment.Text = "Need to work harder"
Case 50 to 59
comment.Text = "Average"
Case 60 to 69
comment.Text = "Above Average"
Case 70 to 84
comment.Text = "Good"
Case Else
comment.Text = "Excellence"
End Select
End Sub

Compiled by: Mr. Roel C. Traballo 44


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Name : _______________________ Date Finished: ________ Rating:


Course/Section: _________ Time: ________
Instructor : _______________________

PRACTICE EXERCISE #6: Sample Program: using MessgeBox.Show method with conditional
statement.

Sample Form:

Specifications:
1) TextBox txtFinalGrade
2) Label lblRemarks
1) 3) Button btnTest
4) Button btnClear
2)
5) Button - btnExit

Note: Use & symbol for short cut keys


3) 4) 5) Example:
Text Property: &Test, &Clear, E&xit

Sample
Output:

Source Codes:
Private Sub btnTest_Click(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles btnTest.Click
If txtFinalGrade.Text >= 74.5 Then
lblRemarks.Text = "Passed"
Else
lblRemarks.Text = "Failed"
End If
End Sub

Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e


As System.EventArgs) Handles btnClear.Click
txtFinalGrade.Text = ""
lblRemarks.Text = ""
End Sub

Compiled by: Mr. Roel C. Traballo 45


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e


As System.EventArgs) Handles btnExit.Click
Close()
End Sub

Modified Codes #1: Using MessageBox.Show method with .Focus( ) Method

Private Sub btnTest_Click(ByVal sender As System.Object, ByVal e


As System.EventArgs) Handles btnTest.Click

If txtFinalGrade.Text >= 74.5 Then


lblRemarks.Text = "Passed"
Else
lblRemarks.Text = "Failed"
End If
End Sub

Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e


As System.EventArgs) Handles btnClear.Click
txtFinalGrade.Text = ""
txtFinalGrade.Focus()
lblRemarks.Text = ""
End Sub

Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e


As System.EventArgs) Handles btnExit.Click
Dim Response As Integer

Response = MessageBox.Show("Close Program...", "Exit", _


MessageBoxButtons.YesNo, MessageBoxIcon.Question)

If Response = DialogResult.Yes Then


Close()
End If
End Sub

Modified Codes #2: Using Try and Catch

Private Sub btnTest_Click(ByVal sender As System.Object, ByVal e


As System.EventArgs) Handles btnTest.Click

Compiled by: Mr. Roel C. Traballo 46


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Dim FinGrd As Single

Try
FinGrd = CDbl(txtFinalGrade.Text)

If FinGrd >= 74.5 Then


lblRemarks.Text = "Passed"
Else
lblRemarks.Text = "Failed"
End If

Catch MyError As InvalidCastException


MessageBox.Show("Pls. enter valid data","Invalid Data")
txtFinalGrade.Text = ""
txtFinalGrade.Focus()
End Try
End Sub

Compiled by: Mr. Roel C. Traballo 47


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Name : _______________________ Date Finished: ________ Rating:


Course/Section: _________ Time: ________
Instructor : _______________________

PRACTICE EXERCISE #7:

Radio Button & Check Box


Sample Program:

Radio Buttons:
rdoBSIT
rdoBSCS
rdoBSCpE

Check Boxes:
chkCom
chkEng
chkFil
chkSci
chkMat

Buttons:
btnTestRdoBtn
btnTestChkBox
btnClearAll

Selected Radio button: BSIT in a Message Box


Selected Check boxes: Computer, Filipino & Math in a Message Box

Source Codes:
Private Sub btnTestRdoBtn_Click(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles btnTestRdoBtn.Click

If rdoBSIT.Checked = True Then


MessageBox.Show("Your course is: " + rdoBSIT.Text, "Radio Button")
ElseIf rdoBSCS.Checked = True Then
MessageBox.Show("Your course is: " + rdoBSCS.Text, "Radio Button")
ElseIf rdoBSCpE.Checked = True Then
MessageBox.Show("Your course is: " + rdoBSCpE.Text, "Radio Button")
Else
MessageBox.Show("No course selected...", "Radio Button")
Compiled by: Mr. Roel C. Traballo 48
JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

End If
End Sub

Private Sub btnTestChkBox_Click(ByVal sender As System.Object, ByVal e


As System.EventArgs) Handles btnTestChkBox.Click
Dim Subj As String

If chkCom.Checked Then
Subj = chkCom.Text + vbNewLine
End If

If chkEng.Checked Then
Subj = Subj + chkEng.Text + vbNewLine
End If

If chkFil.Checked Then
Subj = Subj + chkFil.Text + vbNewLine
End If

If chkSci.Checked Then
Subj = Subj + chkSci.Text + vbNewLine
End If

If chkMat.Checked Then
Subj = Subj + chkMat.Text + vbNewLine
End If

MessageBox.Show("Your favorite subject/s is/are:" + vbNewLine +Subj,_


"Check Box")
End Sub

Private Sub btnClearAll_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnClearAll.Click
'To clear radio buttons
rdoBSIT.Checked = False
rdoBSCS.Checked = False
rdoBSCpE.Checked = False
'To clear check boxes
chkFil.Checked = False
chkCom.Checked = False
chkSci.Checked = False
chkEng.Checked = False
chkMat.Checked = False
End Sub

Compiled by: Mr. Roel C. Traballo 49


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Name : _______________________ Date Finished: ________ Rating:


Course/Section: _________ Time: ________
Instructor : _______________________

MACHINE PROBLEM #3:

FORM 1: Sample Interface/Form Layout:

Formula:
Semestral Grade = 25% of Prelim + 25% of
Midterm + 50% of Final

Point Equivalent Table:

Sem Grade Pt. Equivalent


100 1.00
95-99 1.50
90-94 2.00
85-89 2.50
80-84 3.00
75-79 3.50
74 below 5.00

Additional Logical Problems:

For New Entry Button:


Upon clicking displays this message box
If Yes will clear all entries else nothing happen

For Compute Button:


Upon clicking displays this message box
If Yes will display the results else nothing happen

For Exit Button:


Will close the program/application

Compiled by: Mr. Roel C. Traballo 50


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Name : _______________________ Date Finished: ________ Rating:


Course/Section: _________ Time: ________
Instructor : _______________________

MACHINE PROBLEM #4:

FORM 2: Sample Interface/Form Layout:

For Compute button:


Sub-Total will display the amount
based on the selected items (TV size)
Discount will display the amount
based on the selected discount (radio
button)
Net Amount get the difference of
sub-total and discount amount.

Note:
You can select one or more items
(check boxes) (see sample output
below)
If no selected discount percentage the
computer will assume of 0% discount.
If no item selected all labels will have
a value of 0.00.

For Clear All button:


Will deselect all checkboxes and
radio button.
Will clear all labels. (i.e., Sub-Total,
Discount & Net Amount)

For Close Button:


Will close the program/application

Compiled by: Mr. Roel C. Traballo 51


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Name : _______________________ Date Finished: ________ Rating:


Course/Section: _________ Time: ________
Instructor : _______________________

MACHINE PROBLEM #5:

FORM 3: Sample Interface/Form Layout:

Form Name : MPFRM03<FirstLastName> Example: MPFRM03RichardGwapo

PRICES:
Size:
Small Php 100.00
Medium 150.00
Large 200.00

Crust Type:
Thin Crust same as size prices
Thick Crust Plus 50% of size
prices

Drinks:
Soft Drinks Php 20.00
Fruit Juice 15.00
Coffee/Chocolate 25.00

Extra Toppings:
Plus Php 10.00 per extra toppings

Build Pizza Button: will display


message box Your Pizza (see
sample above)
Clear Toppings Button: will uncheck all
check boxes.
Compute Button: will display all values
under Amount frame
Clear All Button: will clear all entries
Exit Button: will close the program.

Compiled by: Mr. Roel C. Traballo 52


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Random Function:
Visual Studio .NET provides a pseudo-random number generator, which is a device that
produces a sequence of numbers that meet certain statistical requirements for randomness.

To use the pseudo-random number generator in a procedure, you first create a Random object
Syntax:
Dim objectname as New Random

The Random object represents the pseudo-random number generator in the procedure.

After creating a Random object, you can generate random integers using the Random.Next
method.
Syntax:
randomObject.Next(minValue, maxValue - 1)
Examples Result
#1: Creates a Random object named GenRnd, then
Dim GenRnd As New Random displays (in the lblRndNum control) a random
lblRndNum.Text = GenRnd.Next(0,51) integer that is equal to 0, but less than 51
#2: Creates a Random object named GenRnd, then
Dim GenRnd As New Random displays (in the lblRndNum control) a random
lblRndNum.Text = GenRnd.Next(50,100) integer that is equal to 50, but less than 100
#3: Creates a Random object named GenRnd, then
Dim GenRnd As New Random displays (in the lblRndNum control) a random
lblRndNum.Text = GenRnd.Next(-10,0) integer that is equal to is equal to -10, but less
than 0

Compiled by: Mr. Roel C. Traballo 53


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Name : _______________________ Date Finished: ________ Rating:


Course/Section: _________ Time: ________
Instructor : _______________________

PRACTICE EXERCISE #8:

Sample Program: using Random generator:

Change objects name/properties to:


Computer Generated Number Label1: Computer Generated Number
Name: txtNumber
TextBox1 BorderStyel: Fixed3D
Text: None
Buton1:
Name: btnTest
Text : &TEST

Sample Output:

Source Codes:
Private Sub btnTest_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnTest.Click
Dim GenRnd As New Random

txtNumber.Text = GenRnd.Next(1, 10)

End Sub

Compiled by: Mr. Roel C. Traballo 54


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Modified Source Codes: with sample output

Output for incorrect guess Output for correct guess

Private Sub btnTest_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnTest.Click
Dim GenRnd As New Random
Dim GuessNum, GenRndNum As Integer

Try
GuessNum = CInt(txtNumber.Text)
GenRndNum = GenRnd.Next(1, 10)

If GuessNum = GenRndNum Then


MessageBox.Show("That's correct!", "Guessing Game", _
MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
MessageBox.Show("That's Wrong" + vbNewLine + _
"The correct Answer is: " + CStr(GenRndNum), _
"Guessing Game", MessageBoxButtons.OK, _
MessageBoxIcon.Information)
End If

Catch MyError As InvalidCastException


MessageBox.Show("Pls. enter a number...", "Guessing Game")

End Try
txtNumber.Text = ""
txtNumber.Focus()
End Sub

Compiled by: Mr. Roel C. Traballo 55


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Name : _______________________ Date Finished: ________ Rating:


Course/Section: _________ Time: ________
Instructor : _______________________

PRACTICE EXERCISE #9:

Sample Program: Lucky Seven (with Logical Operators and Random Class)

Specification:
Add 3 labels
o Label1, Label2 & Label3
Name: lblNum1, lblNum2, lblNum3
BorderStyel: FixedSingle
FontSize: 20 FontStyle: Bold
Text: None
TextAlign: MiddleCenter
o Button
Name: btnSpin
Text: &SPIN

Output: If one of the labels has a value 7

Output: If no one has a value 7

Source codes:
Private Sub btnSpin_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnSpin.Click

Dim RndGen As New Random


Dim N1, N2, N3 As Integer

Compiled by: Mr. Roel C. Traballo 56


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

N1 = RndGen.Next(1, 10)
N2 = RndGen.Next(1, 10)
N3 = RndGen.Next(1, 10)

lblNum1.Text = N1
lblNum2.Text = N2
lblNum3.Text = N3

If N1 = 7 Or N2 = 7 OrElse N3 = 7 Then
MessageBox.Show("Congrats! You win...", "Lucky Seven")
Else
MessageBox.Show("Sorry! You lose...", "Lucky Seven")
End If
End Sub

Compiled by: Mr. Roel C. Traballo 57


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Name : _______________________ Date Finished: ________ Rating:


Course/Section: _________ Time: ________
Instructor : _______________________

MACHINE PROBLEM #6: (Create a new Solution)

FORM #1: 3 Digits Lotto Program

Instructions:
1. Your bet should not be less than 10 pesos, otherwise it will prompt you with Enter
minimum amount of Php 10.00
2. Enter single digit for each of the text box (Note: no repeating number/digit per textbox)
3. If the content of the text box are all equal to the winning numbers (in order and no
repeating number/digit also) it will prompt you with You have won 1 MILLION PESOS
JACKPOT (see sample Message box below), otherwise it will prompt you with Sorry
better luck next time
4. But, if the content of the text box are equal to the winning numbers (but not in order) it
will prompt you with You have won a consolation prize of ____. The consolation
prizes will depend on the BET amount (Example: Bet is 100, multiply your bet to
1,000.00 to get the consolation amount.)

Output for Jackpot Output for Consolation prize

Compiled by: Mr. Roel C. Traballo 58


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Name : _______________________ Date Finished: ________ Rating:


Course/Section: _________ Time: ________
Instructor : _______________________

PRACTICE EXERCISE #10:

Combo Box, List Box & NumericUpDown


Sample Program: without discount

Specifications:
ListBox
o Name: lstParts
o Items: see items in the figure
ComboBox
o Name: cboDisc
o Items: 5%, 10%, 15% & No
Discount
Label (Name:)
o lblUPrice
o lblSubTot
o lblDisc
o lblTotAmt
o TextAlign: Right

Sample Output: with discount


NumericUpDown
o Name: nudQuan
o Minimum: 0
o Maximum: 100
Button (Names:)
o btnCompute
o btnClear
o btnClose

Computer Parts Prices


Monitor 2,000.00
Keyboard 250.00
Mouse 100.00
Hard Disk 1,000.00
Disk Drive 200.00

Compiled by: Mr. Roel C. Traballo 59


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Source Codes:

Private Sub btnCompute_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnCompute.Click

Dim Price, SubTot, TotAmt, Disc, Quan As Single

If lstParts.SelectedIndex = 0 Then
Price = 2000
ElseIf lstParts.SelectedIndex = 1 Then
Price = 250
ElseIf lstParts.SelectedIndex = 2 Then
Price = 100
ElseIf lstParts.SelectedIndex = 3 Then
Price = 1000
ElseIf lstParts.SelectedIndex = 4 Then
Price = 200
Else
MessageBox.Show("No selected item...", "Computer Store")
Exit Sub
End If

Quan = nudQuan.Text
If Quan = 0 Then
MessageBox.Show("Pls. enter quantity", "Computer Store")
Exit Sub
End If

lblUPrice.Text = FormatNumber(Price, 2)
SubTot = Price * Quan
lblSubTot.Text = FormatNumber(SubTot, 2)

If cboDisc.SelectedIndex = 1 Then
Disc = SubTot * 0.05
ElseIf cboDisc.SelectedIndex = 2 Then
Disc = SubTot * 0.1
ElseIf cboDisc.SelectedIndex = 3 Then
Disc = SubTot * 0.15
Else
Disc = 0
End If
lblDisc.Text = FormatNumber(Disc,2)
TotAmt = SubTot - Disc
lblTotAmt.Text = FormatNumber(TotAmt, 2)
End Sub
Compiled by: Mr. Roel C. Traballo 60
JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnClose.Click
Dim Ans As Integer

Ans = MessageBox.Show("Do want to close the program", "Close",_


MessageBoxButtons.OKCancel, MessageBoxIcon.Question)

If Ans = DialogResult.OK Then


Close()
End If
End Sub

Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnClear.Click
lstParts.ClearSelected()
cboDisc.Text = ""
lblUPrice.Text = ""
nudQuan.Text = 0
lblDisc.Text = ""
lblSubTot.Text = ""
lblTotAmt.Text = ""
End Sub

Compiled by: Mr. Roel C. Traballo 61


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Name : _______________________ Date Finished: ________ Rating:


Course/Section: _________ Time: ________
Instructor : _______________________

PRACTICE EXERCISE #11:

Sample Program: using List Box & RichTextBox control/object

Specification:
GroupBox: (2)
ListBox
o Name: lstTerms
o Items: see items in the
figure
RichTextBox
o Name: rchMeaning

Source Codes:

Private Sub lstTerms_DoubleClick(ByVal sender As Object, ByVal e As


System.EventArgs) Handles lstTerms.DoubleClick

Dim Means As String


Select Case lstTerms.SelectedIndex
Case 0
Means = " - A small piece of message that is transported over the
Internet."
Case 1
Means = " - A special-purpose computer that directs packets of data
along a network."
Case 2
Means = " - A security mechanism that organizations use to protect their
intranet from the Internet."
Case 3
Means = " - A program that allows you to log into a remote computer."
Case 4
Means = " - A set of precisely specified rules for carrying out a
procedure."
End Select
rchMeaning.Text = Means
End Sub

Compiled by: Mr. Roel C. Traballo 62


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Sample Output:

Modified Source Codes:


-----------------------------------------------------------------------
Private Sub lstTerms_DoubleClick(ByVal sender As Object, ByVal e As
System.EventArgs) Handles lstTerms.DoubleClick
Dim Means As String
Dim i As Byte

Select Case lstTerms.SelectedIndex


Case 0
Means = " - A small piece of message that is
transported over the Internet."
Case 1
Means = " - A special-purpose computer that directs
packets of data along a network."
Case 2
Means = " - A security mechanism that organizations
use to protect their intranet from the Internet."
Case 3
Means = " - A program that allows you to log into a
remote computer."
Case 4
Means = " - A set of precisely specified rules for
carrying out a procedure."
End Select

For i = 0 To 4
If lstTerms.SelectedIndex = i Then
rchMeaning.Text = lstTerms.Items.Item(i) + Means
End If
Next i
End Sub

----------------------------------------------------------------------
-
Sample Output:

Compiled by: Mr. Roel C. Traballo 63


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Name : _______________________ Date Finished: ________ Rating:


Course/Section: _________ Time: ________
Instructor : _______________________

PRACTICE EXERCISE #12:


Sample Program: 2 List Box control/object

Sample Output:

Specifications:
2 list box (Name: lst1 & lst2
respectively)
2 buttons

Source Codes:
Private Sub lst1_DoubleClick(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles lst1.DoubleClick

If lst1.SelectedIndex = 0 Then
lst2.Items.Add(lst1.SelectedItem)
End If
If lst1.SelectedIndex = 1 Then
lst2.Items.Add(lst1.SelectedItem)
End If
If lst1.SelectedIndex = 2 Then
lst2.Items.Add(lst1.SelectedItem)
End If
End Sub

Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnClear.Click

Compiled by: Mr. Roel C. Traballo 64


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Dim i As Integer

For i = 0 To lst2.Items.Count
If lst2.SelectedIndex = i Then
lst2.Items.RemoveAt(i)
End If
Next i
End Sub

Private Sub btnClearAll_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnClearAll.Click
lst1.ClearSelected()
lst2.Items.Clear()
End Sub

Modified Source Codes:


Private Sub lst1_DoubleClick(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles lst1.DoubleClick

Dim i As Byte
For i = 0 To lst1.Items.Count
If lst1.SelectedIndex = i Then
lst2.Items.Add(lst1.SelectedItem)
End If
Next
End Sub

Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnClear.Click
Dim i As Integer
For i = 0 To lst2.Items.Count
If lst2.SelectedIndex = i Then
lst2.Items.RemoveAt(i)
End If
Next i
End Sub

Private Sub btnClearAll_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnClearAll.Click

lst1.ClearSelected()
lst2.Items.Clear()
End Sub

Compiled by: Mr. Roel C. Traballo 65


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Name : _______________________ Date Finished: ________ Rating:


Course/Section: _________ Time: ________
Instructor : _______________________

MACHINE PROBLEM #7:

Project Name : MPPJT01<FirstLastName> Example: MPPJT01RichardGwapo


Form Name : MPFRM02<FirstLastName> Example: MPFRM02RichardGwapo

FORM #2: Tuition Fee Computation

Instructions:
Define your own controls/objects
name
Course: (ComboBox)
o Items: BSIT, BSCS, BSA, BSN
Year Level: (ListBox)
o Items: Freshem, Sophomore,
Junior, Senior
Total Units: (NumericUpDown)
o Minimum: 3
o Maximum: 30
Lab. Units: (NumericUpDown)
o Minimum: 0
o Maximum: 3

Tuition Fee per unit: Php 100.00


Lab. Fee per unit: Php 1,000.00
Miscellaneous Fees:
Year Level BSIT/BSCS BSA/BSN
Freshmen 1,000.00 2,000.00
Sophomore 750.00 1,500.00
Additional Logical Problems: Junior 500.00 1,000.00
Senior 250.00 500.00
For Calculate button:
o Will compute for Tuition Fee, Lab. Fee , Misc. Fee & Total Fee:
Note:
- If no selected Course and/or Year Level will display a message/prompt with No
course selected and/or No year level selected
- Label values will retain to empty.
For Clear button:
o Will clear Course ComboBox
o Will deselect Year Level ListBox
o Will clear all Labels
o Will reset to zero (0) two NumericUpDown
For Close button:
o Will close the program/application
Note: Format all value in labels using any formatting numbers functions

Compiled by: Mr. Roel C. Traballo 66


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Name : _______________________ Date Finished: ________ Rating:


Course/Section: _________ Time: ________
Instructor : _______________________

MACHINE PROBLEM #8:

Project Name : MPPJT01<FirstLastName> Example: MPPJT01RichardGwapo


Form Name : MPFRM03<FirstLastName> Example: MPFRM03RichardGwapo

FORM #3: Employee Payroll Computation

EMPLOYEE PAYROLL COMPUTATION

Logical Problems & Formulas:

Position Code Rate/Day Civil Status TAX Rate Basic Pay SSS Rate
A 500.00 Single 10% 10,000 & above 7%
B 400.00 Married 5% 5,000 9,999 5%
C 300.00 Widowed 5% 1,000 4,999 3%
below 1,000 1%

Basic Pay = No. of Days Worked * Rate/Day


SSS Contribution = Basic Pay * SSS Rate
Withholding Tax = Basic Pay * Tax Rate
Net Pay = Basic Pay (SSS Contribution + Withholding Tax)

Upon choosing the desired Employee Number, it will automatically display the Employee Name.
For Compute Button, will compute the Basic Pay, SSS Contribution, Withholding Tax and Net Pay
For Clear Button, will clear all entries
For Quit Button, will close the program/application.

Compiled by: Mr. Roel C. Traballo 67


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Name : _______________________ Date Finished: ________ Rating:


Course/Section: _________ Time: ________
Instructor : _______________________

PRACTICE EXERCISE #13:

DateTimePicker & DateDiff Function


Sample Program:

Specifications:
Buttons:
o btnIn
o btnOut
o btnCompute1
o btnCompute2
Label:
o lblTotDays
DateTimePicker
o dtpIn
o dtOut
TextBox:
o txtIn
o txtOut

Source Codes:
Private Sub btnIn_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnIn.Click
txtIn.Text = Today
End Sub

Private Sub btnOut_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnOut.Click
txtOut.Text = Today
End Sub

Private Sub btnCompute1_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnCompute1.Click
lblTotDays.Text = DateDiff("d", txtIn.Text, txtOut.Text)
End Sub

Private Sub btnCompute2_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnCompute2.Click
lblTotDays.Text = DateDiff("d", dtpIn.Text, dtpOut.Text)
End Sub

Compiled by: Mr. Roel C. Traballo 68


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Name : _______________________ Date Finished: ________ Rating:


Course/Section: _________ Time: ________
Instructor : _______________________

MACHINE PROBLEM #9:

FORM #4: Hotel Billing System

Room Room Type Rate/day Type of Additional


Capacity Payment Charge
Regular 100.00 Cash No addl charge
Single De Luxe 300.00 Check + 5%
Suite 500.00 Credit Card + 10%
Regular 200.00
Double De Luxe 500.00
Suite 800.00
Regular 500.00
Family De Luxe 750.00
Suite 1,000.00

Problem:
Compute for Total Amount based on the date of check-in and check-out.
Select room capacity, room type and payment type before clicking Compute button
otherwise, will prompt you with No selected room capacity or No selected room type
or No selected type of payment

Note: If the customer checked-in and checked-out on the same day will charge him/her of 1 day.

Compiled by: Mr. Roel C. Traballo 69


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Name : _______________________ Date Finished: ________ Rating:


Course/Section: _________ Time: ________
Instructor : _______________________

PRACTICE EXERCISE #14:

Program Password:

Instructions:
Create a new solution and project
o Form #1: Password Entry (Sample form interface/layout)
o Change object/control properties as stated below
Message for correct password
Specifications:
Form1:
o Name: frmPass
TextBox:
o Name: txtPass
o PasswordChar: @
o MaxLength: 5
Button: Message for incorrect password
o Name: btnAccept

Type the codes below for Button Accept:


Private Sub btnAccept_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnAccept.Click

If UCase(txtPass.Text) = "GWAPO" Then


MessageBox.Show("Password Accepted...", "Password Entry",
MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
MessageBox.Show("Invalid Password ...", "Password Entry",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If
End Sub

Save and run/execute the program

Compiled by: Mr. Roel C. Traballo 70


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Continuation

Modify the form and source codes: (see sample below)


Additional Objects/Controls:
TextBox
o Name: txtUser
Button
o Name: btnCancel

Message for incorrect password after the 3rd trial

Modify the source codes (Part I): (Password can only enter 3 times)

btnAccept.Click
Private Sub btnAccept_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnAccept.Click
Dim Answer As Integer
Static Trial As Byte

If UCase(txtPass.Text) = "GWAPO" Then


MessageBox.Show("Password Accepted...", "Password Entry",
MessageBoxButtons.OK, MessageBoxIcon.Information)
Me.Hide()
Else
If Trial = 2 Then
MessageBox.Show("Unauthorized user keep out...",
"Password Entry", MessageBoxButtons.OK, MessageBoxIcon.Stop)
Close()
Else
Answer = MessageBox.Show("Invalid Password ...Try again?",
"Password Entry", MessageBoxButtons.RetryCancel,
MessageBoxIcon.Question)
If Answer = DialogResult.Retry Then
Trial = Trial + 1
txtPass.Text = ""
txtPass.Focus()
Else
Close()
Compiled by: Mr. Roel C. Traballo 71
JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

End If
End If
End If
End Sub

btnCancel.Click
Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnCancel.Click
Close()
End Sub

Save and run/execute the program

Continuation
Add new form to your existing solution / project

o Form #2: Transaction


o Change object/control properties as stated
below
Form2:
o Name: frmTransaction

Modify the source codes (Part II): (Executing Transaction form if the password is correct)

btnAccept.Click
Private Sub btnAccept_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnAccept.Click

Dim frmTrans As frmTransaction


Dim Answer As Integer
Static Trial As Byte

frmTrans = New frmTransaction

If UCase(txtPass.Text) = "GWAPO" Then


MessageBox.Show("Password Accepted...", "Password Entry",
MessageBoxButtons.OK, MessageBoxIcon.Information)
Me.Hide()
frmTrans.Show()

Compiled by: Mr. Roel C. Traballo 72


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Else
If Trial = 2 Then
MessageBox.Show("Unauthorized user keep out...", "Password
Entry", MessageBoxButtons.OK, MessageBoxIcon.Stop)
Close()
Else
Answer = MessageBox.Show("Invalid Password ...Try again?",
"Password Entry", MessageBoxButtons.RetryCancel,
MessageBoxIcon.Question)
If Answer = DialogResult.Retry Then
Trial = Trial + 1
txtPass.Text = ""
txtPass.Focus()
Else
Close()
End If
End If
End If
End Sub
Save and run/execute the program

Continuation.

MenuStrip (Inserting Menu Items)


Add MenuStrip object/control to your transaction
form
o MenuStrip1 will be displayed at the bottom of
the screen (but not within the form) (see figure
below)
Menus:
o &File
&Open
E&xit
o &Help
&About

Compiled by: Mr. Roel C. Traballo 73


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

ToolStrip and ImageList Controls


MDI Form
Menu Bar
Tool Strip
Image List

MDI Child
Form

Compiled by: Mr. Roel C. Traballo 74


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Name : _______________________ Date Finished: ________ Rating:


Course/Section: _________ Time: ________
Instructor : _______________________

MACHINE PROBLEM #10:

Solution Name : Same Solution (New project)


Project Name : MPPJT02<FirstLastName> Example: MPPJT02RichardGwapo
Form Name : MPFRM01<FirstLastName> Example: MPFRM01RichardGwapo

FORM #1: Presidential Elections 2010


Voters ID Entry

For Validate button:


o If the Voters ID is correct
will display a message box
as shown in the figure.
o Click OK button to launch
Form 2 (see form 2
below).

FORM #2:
Presidential Candidates
Cast your vote by clicking the
ComboBox and choose your desired
candidate.
For Vote button:
o Click Vote button to confirm
your vote
o Then, the voted candidate
will automatically display
his votes as shown in the
Actual Tally
For Result button:
o Click Result button to
display the result. (see
sample output below
o

For Close button:


o Click Close button to go
back to the 1st form (Form
#1)

Compiled by: Mr. Roel C. Traballo 75


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Name : _______________________ Date Finished: ________ Rating:


Course/Section: _________ Time: ________
Instructor : _______________________

PRACTICE EXERCISE #15:

PictureBox Control

Sample Program:

Specifications:
PictureBox
o picBaby
Button
o btnShow
o btnHide
o btnEnable
o btnDisable

Source Codes:

Private Sub btnShow_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnShow.Click
picBaby.Visible = True
End Sub

Private Sub btnHide_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnHide.Click
picBaby.Visible = False
End Sub

Private Sub btnEnable_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnEnable.Click
btnShow.Enabled = True
btnHide.Enabled = True
End Sub

Private Sub btnDisable_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnDisable.Click
btnShow.Enabled = False
btnHide.Enabled = False
End Sub

Compiled by: Mr. Roel C. Traballo 76


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Modified Source Codes: (using sender argument)

Private Sub btnAction_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnShow.Click, btnDisable.Click,
btnEnable.Click, btnHide.Click
If sender Is btnShow Then
picBaby.Visible = True
ElseIf sender Is btnHide Then
picBaby.Visible = False
ElseIf sender Is btnEnable Then
btnShow.Enabled = True
btnHide.Enabled = True
ElseIf sender Is btnDisable Then
btnShow.Enabled = False
btnHide.Enabled = False
End If
End Sub

Compiled by: Mr. Roel C. Traballo 77


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Arrays
All of the variables have been used are simple variables. A simple variable, also called a
scalar variable, is one that is unrelated to any other variable in memory.
In many applications, however, you may need to reserve a block of related variables,
referred to as an array
An array is a group of variables that have the same name and data type and are related in
some way. For example, each variable in the array might contain an employee record such as
name, sss number, basic rate and so on. It may be helpful to picture an array as a group of small,
adjacent boxes inside the computer's memory. You can write information to the boxes and so
you can read information from the boxes; you just cannot see the boxes.

Syntax #1:
accessibility arrayname(index) As datatype

Syntax #2:
accessibility arrayname( ) As datatype = {array elements}

Examples & Results


Ex. 1: Dim Cities(3) as String

- declares a four-element array named Cities; each element is automatically initialized


to a zero-length (empty) string
Ex. 2: Private Numbers(5) as Integer

- declares a six-element array named Numbers; each element is automatically


initialized to the number zero (0)
Ex. 3: Private Names( ) As String = {Richard,Noli,Lester,Val}

- declares and initializes a four-element array named Names


Ex. 4: Dim Scores( ) As Integer = {75, 85, 90, 80}

- declares and initializes a four-element array named Scores.

Storing Data in a One-Dimensional Array


Examples & Results
Ex. 1:

Cities(0) = Pasig
Cities(1) = Mandaluyong
Cities(2) = Quezon City
Cities(3) = Makati

- assigning the strings Pasig, Mandaluyong and Quezon City to the Cities array,
replacing the zero-length (empty) string stored in the array.

Compiled by: Mr. Roel C. Traballo 78


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Ex. 2:

Dim X as Integer
For X = 0 to 3
Total = Total + Scores(X)
Next

- will get the total scores of array Scores and store the value in variable Total

Compiled by: Mr. Roel C. Traballo 79


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Name : _______________________ Date Finished: ________ Rating:


Course/Section: _________ Time: ________
Instructor : _______________________

PRACTICE EXERCISE #16:

Sample Program #1:

Specifications:
ListBox
o lstNames
o lstScores
Button
o btnView
o btnClear
o btnExit
Label
o Label1, Label2, Label3
o lblAve

Source Codes: Array1


Private Sub btnView_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnView.Click
Dim Names() As String = {"Richard", "Noli", "Lester", "Val"}
Dim Scores() As Single = {100, 80, 70, 95}
Dim i As Integer
Dim Total As Single = 0

For i = 0 To Names.Length - 1 'or => For i = 0 to 3


lstNames.Items.Add(Names(i))
lstScores.Items.Add(Scores(i))
Total += (Scores(i))
Next
lblAve.Text = Total / Scores.Length
End Sub

Compiled by: Mr. Roel C. Traballo 80


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnClear.Click
lstNames.Items.Clear()
lstScores.Items.Clear()
lblAve.Text = ""
End Sub

Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnExit.Click
Close()
End Sub

Compiled by: Mr. Roel C. Traballo 81


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Name : _______________________ Date Finished: ________ Rating:


Course/Section: _________ Time: ________
Instructor : _______________________

PRACTICE EXERCISE #17:

Sample Program #2:

Specifications:
ComboBox
o cboMon
o cboDay
o cboYr

Source Codes: Array2


Private Sub Array2_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Dim Months() As String = {"January", "February", "March", _
"April", "May", "June", "July","August", "September", _
"October", "November", "December"}
Dim i, Len, yr As Integer
Len = Months.Length - 1
For i = 0 To Len
cboMon.Items.Add(Months(i))
Next
For i = 1 To 31
cboDay.Items.Add(i)
Next
yr = Today.Year 'or Format(Now, "YYYY")
While yr >= 1970
cboYr.Items.Add(yr)
yr -= 1
End While
End Sub

Sample Program #3:

Specifications:
ListBox
o lstStud
Button
o btnShow
o btnSort

<- Original Data:

Sorted Data ->

Compiled by: Mr. Roel C. Traballo 82


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Name : _______________________ Date Finished: ________ Rating:


Course/Section: _________ Time: ________
Instructor : _______________________

PRACTICE EXERCISE #18:

Source Codes: Array3 using ListBox Sort (=True) Property

Private Sub btnSort_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnSort.Click
lstStud.Sorted = True
End Sub
-----------------------------------------------------------------------

Modified Source Codes: using Array

Public Class Array3

Dim Studs() As String _


= {"Traballo, Richard", "Argente, Noli", "Diampoc, Lester", _
"Guarin, Rudolph Val", "Valderama, Arlene Mae", "Taduyo, Mary _
Anne", "Cervantes, Mary Ellaine", "Pangan, Shirley", "Clemente, _ Gina",
"Villanueva, Luisa", "Ebardo, Ryan", "Hobrero, Alberto", _ "Gumila, Roldan"}
Dim i As Byte

Private Sub btnSort_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnSort.Click
lstStud.Items.Clear()
lstStud.Sorted = True
For i = 0 To Studs.Length - 1
lstStud.Items.Add(Studs(i))
Next
End Sub

Private Sub btnShow_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnShow.Click
lstStud.Items.Clear()
lstStud.Sorted = False
For i = 0 To Studs.Length - 1
lstStud.Items.Add(Studs(i))
Next
End Sub

End Class

Compiled by: Mr. Roel C. Traballo 83


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Name : _______________________ Date Finished: ________ Rating:


Course/Section: _________ Time: ________
Instructor : _______________________

MACHINE PROBLEM #11:

FORM 1: Password Entry

Richard Gwapo

*****

Note: No limit for password, if incorrect password will prompt the user to RETRY & CANCEL
and user name should have an entered value otherwise will prompt the user to enter value for
user name.

If the password is correct will display the 2nd form (MENU)

FORM 2: (with File & Help Menu)


Main Menu: File Help
Sub Menus: Transaction About
Exit

<File> <Transaction>,
will display the Transaction Form (Form 3)

For TRANSACTION Form:


Initially; BUTTONS: New, Clear, Close & Compute are all in disabled layout (as shown below)

<File> <Exit>
will close the program

Compiled by: Mr. Roel C. Traballo 84


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

FORM 3: Transaction

User Name: Railee Darrel <Insert Date & Time here>

Appliances/Items Unit Price Appliances/Items Unit Price


Electric Fan 500.00 Television 5,000.00
Refrigerator 9,000.00 Air Conditioner 10,000.00
Washing Machine 4,000.00 Rice Cooker 600.00
Oven Toaster 550.00 Electric Stove 1,000.00
Flat Iron 350.00 Electric Pot 800.00
VCD Player 1,200.00 Karaoke 2,500.00
Mini Component 3,500.00 Microwave Oven 3,000.00

Logical Problems:
Double click Appliance item (List Box) then the selected item will be displayed to the Appliance
Sold (List Box) and UnitPrice (List Box) (see example below)
Note: Be sure that you have enter value in the Quantity
If quantity is less than or equal to zero (0) it will prompt the user to input quantity.
Amount Text Box will be based on the Appliance Unit Price * Quantity
Example: Appliance Sold: Electric Fan, Unit Price: 500, Quantity: 2 (see example below)
Sub-total Text Box will be based on the total item sold.
Example: Appliance Sold: Air Conditioner 10,000.00 X 1 and Electric Fan 500.00 X 2
(see example below);
Choose Type of Payment: Cash or Charge then, will enable Compute button
If Compute button is clicked; for CASH
Total Amount = Sub-total less 5% discount

Compiled by: Mr. Roel C. Traballo 85


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Output:
For Cash Payment

User Name: Richard Gwapo <Insert Date & Time here>

Then, will enable buttons; New, Clear & Close


Enter value for Amount Tendered:
Amount Tendered should be exact amount or should be greater than Total Amount otherwise, will prompt
the user to enter valid amount.
Click Change button to display the amount change.
For New button, will clear all entries
For Clear button, will clear Quantity, Appliance Sold, Unit Price and Type of Payment only.
If Compute button is clicked; for CHARGE
Total Amount = Sub-total + 5% additional charge
For Close button, will close the transaction window only.

Output:
For Charge Payment.

User Name: Richard Gwapo <Insert Date & Time here>

Compiled by: Mr. Roel C. Traballo 86


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Then, will hide all controls under Total Amount and displays 5% Additional to all Charge
Payments (see example above)

FORM 4:

If Help then About is clicked


will display a Form About the program

If button OK is clicked
will close the form window.

If button AUTHOR is clicked


will display programmers name

Appliance Store

Compiled by: Mr. Roel C. Traballo 87


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Name : _______________________ Date Finished: ________ Rating:


Course/Section: _________ Time: ________
Instructor : _______________________

PRACTICE EXERCISE #19:

ListView Control
Sample Program #1:

Change ListView properties:


Name: lvwInfo
Column: (add 3 ColumnHeader and
change the text as shown in the ListView)
FullRowSelect: True
GridLine: True
View: Details

Source Codes:
Private Sub ListView1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Dim objItem As ListViewItem
objItem = lvwInfo.Items.Add("00001")
With objItem
.SubItems.Add("Traballo, Richard")
.SubItems.Add("BSMath")
End With
objItem = lvwInfo.Items.Add("00002")
With objItem
.SubItems.Add("Argente, Noli")
.SubItems.Add("BSCpE")
End With
objItem = lvwInfo.Items.Add("00003")
With objItem
.SubItems.Add("Diampoc, Lester")
.SubItems.Add("BSCS")
End With
objItem = lvwInfo.Items.Add("00004")
With objItem
.SubItems.Add("Guarin, Rudolph Val")
.SubItems.Add("BSStat")
End With
End Sub
Compiled by: Mr. Roel C. Traballo 88
JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Name : _______________________ Date Finished: ________ Rating:


Course/Section: _________ Time: ________
Instructor : _______________________

PRACTICE EXERCISE #20:

ListView Control & Array


Modified Source Codes: using Array
Private Sub ListView1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Dim objItem As ListViewItem
Dim Num() As String = {"00001", "00002", "00003"}
Dim Names() As String = {"Traballo, Richard", "Argente, Noli", "Diampoc, Lester"}
Dim Course() As String = {"BSMath", "BSCpE", "BSCS"}
Dim i As Byte

For i = 0 To 2
objItem = lvwInfo.Items.Add(Num(i))
With objItem
.SubItems.Add(Names(i))
.SubItems.Add(Course(i))
End With
Next
End Sub
Sample Program #2:

Compiled by: Mr. Roel C. Traballo 89


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Source Codes:
Private Sub btnNew_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnNew.Click
txtSno.Focus()
txtSno.Clear()
txtSna.Clear()
txtCors.Clear()
txtSno.Enabled = True
txtSna.Enabled = True
txtCors.Enabled = True
btnNew.Enabled = False
btnSave.Enabled = True
End Sub

Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnSave.Click

If txtSno.Text = "" Or txtSna.Text = "" Or txtCors.Text = "" Then


MessageBox.Show("Please enter complete data...", _
"Data Entry", MessageBoxButtons.OK, _
MessageBoxIcon.Information)
Else
txtSno.Enabled = False
txtSna.Enabled = False
txtCors.Enabled = False
btnSave.Enabled = False
btnNew.Enabled = True
End If
End Sub

Private Sub btnView_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles btnView.Click
Dim objItem As ListViewItem
objItem = lv.Items.Add(txtSno.Text)
With objItem
.SubItems.Add(txtSna.Text)
.SubItems.Add(txtCors.Text)
End With
End Sub

Private Sub btnRemove_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnRemove.Click
lv.Items.Clear()
End Sub

Compiled by: Mr. Roel C. Traballo 90


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Using Collections
The Controls Collection
The controls contained on a Windows form belong to the Controls collection in Visual
Basic.NET. A collection is simply a group of one or more individual objects treated as one unit. The
Controls collection, for example, contains one or more Control Objects, which can be text boxes, labels,
buttons, and so on.
Visual Basic .NET automatically assigns a unique number, called index, to each Control object in
the Controls collection. The index indicates the Control objects position in the collection. The first
Control object in the Controls collection has an index of zero (0), the second has an index of one (1), and
son on. You can refer to a Control object in the Controls collection using either the syntax
Controls.Item(index) or the syntax Controls(index).

Examples & Results


Ex. 1: Me.MsgLabel.Text = Controls.Item(0).Name

- displays (in the MsgLabel control) the name of the first control contained in the
Controls collection.
Ex. 2: Dim intX As Integer
For intX = 0 To Controls.Count 1
MessageBox.show(Controls.Item(intX).Name, Name, _
MessageBoxButtons.OK, MessageBoxIcon.Information)
Next

- displays (in message boxes) the name of each control contained in the Controls
collection.
Ex. 3: Dim intX As Integer
Do While intX < Controls.Count
If TypeOf Controls.Item(intX) Is TextBox Then
Controls.Item(intX).Text =
End If
intX = intX + 1
Loop

- clears the contents of the textbox controls on the form

Compiled by: Mr. Roel C. Traballo 91


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Creating Sub and Function Procedures


Procedures
A procedure is a block of program code that performs a specific task. Procedures in Visual
Basic .NET can be either Sub procedures or Function procedures. The difference between both types of
procedures is that a Function procedure returns a value after performing its assigned task, whereas a
Sub procedure does not return a value.

Sub Procedures
There are two types of Sub procedures in Visual Basic .NET: event procedures and user-defined
Sub procedures. Most of the procedures that you coded were event procedures. An event procedure is
simply a Sub procedure that is associated with a specific object and event, such as buttons Click event or
a text boxs KeyPress event. Recall that the computers automatically process an event procedure when
the event occurs.

A user-define Sub procedure is independent of any object and event, and is processed only
when called, or invoke, from code. To invoke a user-defined Sub procedure using the Call statement.

A Sub procedure can contain one or more parameters in its procedure header. Each parameter
stores data that is passed to the procedure when it is invoked. For example, all event procedures contain
two parameters: sender and e. The sender parameter contains the internal memory address of the object
that raised the event, and the e parameter contains any traditional information provided by the object. For
instance, when a buttons Click event occurs, the address of the button is passed to the Click event
procedure and stored in the procedures sender parameter. No additional information is passed when a
Click event occurs, so no information is stored in a Click event procedures e parameter.

Like the procedure header for an event procedure, the procedure header for a user-defined Sub
procedure also can include one or more parameters.

Sub Procedure Syntax:


Accessibility Sub procedurename([parameterlist])
[statements]
End Sub

Examples:
Ex. 1: Procedure that clears the contents of the textbox controls on the form

Private Sub ClearTextBox( ) procedure with no parameter


txt1.Text =
txt2.Text =
txt3.Text =
End Sub

Ex. 2: Procedure that clears the contents of the textbox controls on the form using
Collection

Compiled by: Mr. Roel C. Traballo 92


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Private Sub ClearTextBox( )


Dim intX As Integer
Do While intX < Controls.Count
If TypeOf Controls.Item(intX) Is TextBox Then
Controls.Item(intX).Text =
End If
intX = intX + 1
Loop
End Sub

Ex. 3:

Private Sub GetInfoButton_Click (ByVal sender As Object, ByVal e As _


System.EventArgs) Handles GetInfoButton.Click

Dim Name, Age As String


Name = InputBox(Enter your name: , Name)
Age = InputBox(Enter your age: , Age)
Call DisplayMsg(Name,Age)
End Sub

Private sub DisplayMsg(ByVal Neym As String, ByVal Year As String)


MessageBox.show(Your name is: & Neym & vbNewLine & _
Your age is: & Year)
End Sub

Ex. 4:

Private Sub CalcButton_Click (ByVal sender As Object, ByVal e As _


System.EventArgs) Handles CalcButton.Click

Dim intRegion1, intRegion2 As Integer


Dim sngBonus As Single

intRegion1 = Val(txtRegion1.Text)
intRegion2 = Val(txtRegion2.Text)
sngBonus = Val(txtBonus.Text)

Call DisplayBonus(intRegion1, intRegion2, sngBonus)


End Sub

Compiled by: Mr. Roel C. Traballo 93


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Private Sub DisplayBonus(ByVal intSale1 As Integer, _


ByVal intSale2 As Integer, ByVal sngRate As Integer)

Dim intTotal As Integer, sngBonusRate As Single

intTotal = intSale1 + intSale2


sngBonusRate = intTotal * sngRate
lblBonus.Text = Format(sngBonusRate, currency)
End Sub

Function Procedures
Like a Sub procedure, a Function procedure, typically referred to simply as a function, is a
block of code that performs a specific task. However, unlike a Sub procedure, a function returns a value
after completing the task. Some functions, such as the Val and InputBox functions, are intrinsic to
Visual Basic .NET.

InputBox Function
returns the users response to a prompt that appears in a dialog box.

Syntax:
Var-name = InputBox (Message, Title, Default-Value)

Ex:
Dim Name As String
Name = InputBox(Enter your name: , Name Entry, Richard Gwapo)

If Name = Richard Gwapo Then


MessageBox.show(You accepted the default value: & Name)
Else
MessageBox.show(Your name is: & Name)
End If

Sample output of InputBox Function:

Compiled by: Mr. Roel C. Traballo 94


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Function Procedure Syntax:


Accessibility Function procedurename([parameterlist]) As datatype
[statements]

Return expression
End Sub

Example:
Private Sub BonusButton_Click (ByVal sender As Object, ByVal e As _
System.EventArgs) Handles BonusButton.Click

Dim intRegion1, intRegion2 As Integer


Dim sngBonus As Single

intRegion1 = Val(txtRegion1.Text)
intRegion2 = Val(txtRegion2.Text)
sngBonus = CalcBonus(intRegion1, intRegion2, 0.05)
lblBonus.Text = Format(sngBonus, currency)
End Sub

Private Function CalcBonus(ByVal intSale1 As Integer, _


ByVal intSale2 As Integer, _
ByVal sngRate As Single) As Single
Dim intTotal As Integer

intTotal = intSale1 + intSale2


Return intTotal * sngRate
End Function

Compiled by: Mr. Roel C. Traballo 95


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

An Introduction to Database Concepts and Programming

One of the most important in Visual Basic Programming is the management of data.
Before we move to the details of accessing data from a database using Visual Basic, it is a good
idea to recollect some important concepts of a database.

A collection of related information stored in an organized way is termed as a database.


This helps application programs to easily access data. Information in a database is stored in the
form of tables where each row of the table is called record and each column of the table is called
field. The intersection of the row and column is called an item.

Cursors
The name cursor probably originated from the blinking cursor on a computer terminal.
Just as a cursor indicates the current position on the screen and where the typed words
will appear next, a cursor on a result set indicates the current position in the result set and
what rows will be returned next.
We can define cursor as a result set where browsing is enabled and the current position of
a record is known.

Types of cursors
Dynamic Cursor
o Dynamic cursor detect all additions, changes and deletions made to the rows in
the result set, regardless of whether the changes occur from inside the cursor or by
other users outside the cursor.
o Dynamic cursors provide forward and backward scrolling.
Keyset Cursor
o Keyset cursors are controlled by a set of unique identifiers (keys) known as the
keyset. These keys are a set of columns of the result set that uniquely identify the
rows in the result set.
o A keyset cursor behaves like dynamic cursor, except that we cannot view records
that other users add, and prevents access to records that other users delete. But
we can still view the changes made to the data by other users.
o It allows forward and backward scrolling through the result set.
Static Cursor
o The static cursor always displays the result set as it was when the cursor was first
opened. They provide forward and backward scrolling.
o Static cursors do not detect updates, deletes, and inserts made by other users. For
example, suppose a static cursor fetches a row and another application then
updates that row. If the application re-fetches the row from the static cursor, the
values if sees are unchanged, despite the changes made by the other application.
Forward-Only Cursor
o This is the default cursor type. It enables to only move forward through the result
set. A forward-only cursor does not support forward of backward scrolling in the
result set, it only supports fetching the rows serially from the start to the end of
the result set.
o If an application does not require scrolling through the result set, the forward-only
cursor is the best way for retrieving data quickly.
Compiled by: Mr. Roel C. Traballo 96
JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Types of Cursor:

Cursor Type ADO Constant Description


Forward Only CursorTypeEnumadOpenForwardOnly Behaves like a dynamic cursor
excepts that it allows to scroll only
forward through records
Keyset CursorTypeEnumadOpenKeyset Prevents us from seeing records
that other users add, and prevents
access to records that other users
delete.
Dynamic CursorTypeEnumadOpenDynamic Allows additions, changes, and
deletions by other users, and
allows all types of movement
through the Recordset
Static CursorTypeEnumadOpenStatic Allows all type of movement
through the Recordset. Addition,
changes, or deletions by other user
will not be visible.

Lock Type:
- Optional. Indicates the type of locks placed on records during editing.

Lock Type Description


LockTypeEnumadLockReadOnly (Default) Read-only. Data cannot be altered.
LockTypeEnumadLockPessimistic The provider does what is required to ensure
successful editing of the records, by locking the
page containing the record immediately upon
editing. This prevents other users from editing the
record.
LockTypeEnumadLockOptimistic The page containing the record is locked only when
the records are updated. Conflicts arise when two
users attempt to update the same record. The update
is granted to the user who first issues the Update
method
LockTypeEnumadLockBatchOptimistic Uses the BatchUpdate method to write the entire
batch of rows to the Recordset. Allows us to make
modifications on a number of rows without having
to write those changes to the Recordset after each
row.

Options
- Optional, Indicates how the provider should evaluate the Source argument. The values of
this parameter are similar to the Command. Type option of the RecordSource property of
the ADODC. Refer to table below for the values of the Option argument of the Open
method.

Compiled by: Mr. Roel C. Traballo 97


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Primary Fields
Key

AuthorID AuthorName AuthorAdd


A001 Richard Traballo Quezon City
A002 Noli Argente Pasig City
Records A003 Arlene Mae Valderama Mandaluyong City
A004 Lester Diampoc San Juan City
A005 Rudolf Val Guarin Makati City

The Author Table

Compiled by: Mr. Roel C. Traballo 98


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Name: _______________________ Date Finished: ________ Rating:


Course/Section: _________ Time: ________
Instructor : _______________________

PRACTICE EXERCISE #21:


Sample Database Connectivity using Microsoft Access (Sample Form)
Form1:
Open Microsoft Access 2003/2007/2010 and create database & table as shown below:
o Database Name: dbSample
o Table Name: tblSample

Type the records as shown and add 5 more records

Add New Form and 9 controls:


o 4 Labels (Label1, Label2, Label3, Label4)
o 4 TextBoxes (TextBox1, TextBox2, TextBox3, TextBox4)
o 1 DataGridView

Compiled by: Mr. Roel C. Traballo 99


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Form Layout:

Click the DataGridView control <SMART MENU> OR Data Source from the Properties Window
Select <Choose Data Source> and click drop down button
Click <Add Project Data Source>
Data Source Configuration Wizard dialog box will be displayed

Choose Database Source Type: Select <Database> and Click <Next> button

Compiled by: Mr. Roel C. Traballo 100


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Choose a Database Model: Select <Dataset>

Click <Next>
Choose Your Data Connection: Click <New Connection> button

Compiled by: Mr. Roel C. Traballo 101


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Add Connection: Click <Change> button and choose <Microsoft Access Database File (OLE DB)
from the list.
Click <Browse> button and locate and select database file (i.e., dbSample.accdb)

Click <Test Connection> button to check if the connection is successful


Click <OK> button Test connection succeeded
Click <OK> button
Click <Finish> button, then Click <Yes> button
Click <Next> button

Compiled by: Mr. Roel C. Traballo 102


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Save the Connection String to the Application Configuration File

Click <Next> button


Choose Your Database Objects:

Put a check on <Tables> (i.e., tblSample)


Click <Finish> button

Compiled by: Mr. Roel C. Traballo 103


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Run the program:

Set DataBindings
Select the first TextBox (TextBox1)
Click DataBindings from the Properties Window
o Text (click dropdown button)
o TblSampleBindingSource
o id
Do the same to the remaining TextBoxes
o TextBox2 = neym
o TextBox3 = kors
o TextBox4 = yir
Run the program

Compiled by: Mr. Roel C. Traballo 104


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Name: _______________________ Date Finished: ________ Rating:


Course/Section: _________ Time: ________
Instructor : _______________________

PRACTICE EXERCISE #22:


Sample Database Connectivity using Microsoft Access (ADD REFERENCE)
Form2:
<Right Click> on Project (WindowsApplication; ie., AccessDatabaseConnect)
Click <Add Reference>

Add Reference: Click <COM> tab and look for <Microsoft ActiveX Data Objects 6.0 Library>

Compiled by: Mr. Roel C. Traballo 105


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

FORM LAYOUT:

Add the following controls


4 Labels
4 TextBoxes (TextBox1 to TextBox4)
5 Buttons
btnNext
btnPrev
btnFirst
btnLast
btnSearch

SOURCE CODES:
Public Class Form2
Dim db As New ADODB.Connection
Dim tbl As New ADODB.Recordset

Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


MyBase.Load
'For Microsoft Access 2007
db.Open("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\dbSample.accdb")
'For Microsoft Access 2003
'db.Open("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=D:\dbSample.mdb")
tbl.Open("select * from tblSample", db, _
ADODB.CursorTypeEnum.adOpenDynamic, _
ADODB.LockTypeEnum.adLockOptimistic)

tbl.MoveFirst()
Call DisplayRecord()
End Sub
-----------------

Private Sub DisplayRecord()


With tbl
TextBox1.Text = .Fields(0).Value 'TextBox1.Text = tbl1.Fields("id").value
TextBox2.Text = .Fields(1).Value
TextBox3.Text = .Fields(2).Value
TextBox4.Text = .Fields(3).Value
End With
End Sub
-----------------

Compiled by: Mr. Roel C. Traballo 106


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Private Sub btnNext_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


btnNext.Click
'On Error Resume Next
With tbl
.MoveNext()
If .EOF = True Then
MsgBox("end of file encountered...")
.MoveLast()
Else
DisplayRecord()
End If

End With
End Sub
-----------------

Private Sub btnPrev_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


btnPrev.Click
tbl.MovePrevious()
If tbl.BOF = True Then
MsgBox("beginning of file encountered...")
tbl.MoveFirst()
Else
Call DisplayRecord()
End If
End Sub
-----------------
Private Sub btnFirst_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
btnFirst.Click
tbl.MoveFirst()
Call DisplayRecord()
End Sub
-----------------

Private Sub btnLast_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnLast.Click


tbl.MoveLast()
Call DisplayRecord()
End Sub
-----------------

Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


btnSearch.Click
Dim idnum As String
idnum = InputBox("Enter id number")

With tbl
.MoveFirst()

Compiled by: Mr. Roel C. Traballo 107


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

.Find("id='" & idnum & "'")


If .EOF = True Then
MsgBox("id number not found...")
Else
Call DisplayRecord()
End If
End With
End Sub
End Class

Compiled by: Mr. Roel C. Traballo 108


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Name: _______________________ Date Finished: ________ Rating:


Course/Section: _________ Time: ________
Instructor : _______________________

PRACTICE EXERCISE #23:


Sample Program (Database Connectivity using ListView)

Control/Objects name:

TextBox Buttons
txt1 btnNext, btnPrev,
txt2 btnFind, btnEdit,
txt3 btnFirst, btnLast,
btnAdd, btnSave,
btnDelete,
btnView

ListView
lvwRecord

Database name: Database.mdb


Table name: Teybol

Field name Field type


num text
name text
course text

Source Codes:
Object declarations:
Public Class Form1
Public db As New ADODB.Connection
Public tbl As New ADODB.Recordset

Form Load event procedure:


Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
db.Open("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & "C:\Database.mdb")
db.Open("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Database.accdb")
tbl.Open("select * from Teybol", db, ADODB.CursorTypeEnum.adOpenDynamic, _
ADODB.LockTypeEnum.adLockOptimistic)
tbl.MoveFirst()

Compiled by: Mr. Roel C. Traballo 109


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Call DisplayRecord()
Call DisabledControl()
End Sub

Next button event procedure:


Private Sub btnNext_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnNext.Click
tbl.MoveNext()
If tbl.EOF = False Then
Call DisplayRecord()
Else
MessageBox.Show("Last record encountered...")
tbl.MoveLast()
End If
End Sub

Previous button event procedure:


Private Sub btnPrev_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnPrev.Click
tbl.MovePrevious()
If tbl.BOF = False Then
DisplayRecord()
Else
MessageBox.Show("Beginning of record encountered...")
tbl.MoveFirst()
End If
End Sub

First button event procedure:


Private Sub btnFirst_Click(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles btnFirst.Click
tbl.MoveFirst()
Call DisplayRecord()
End Sub

Last button event procedure:


Private Sub btnLast_Click(ByVal sender As Object, ByVal e As
System.EventArgs) Handles btnLast.Click
tbl.MoveLast()
Call DisplayRecord()
End Sub

Find button event procedure:

Compiled by: Mr. Roel C. Traballo 110


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Private Sub btnFind_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnFind.Click
Dim n As String
n = InputBox("Enter student number here: ")

With tbl
.MoveFirst()
.Find("num='" & n & "'")
If .EOF = True Then
MsgBox("Student number not found")
Else
Call DisplayRecord()
End If
End With
End Sub

Add button event procedure:


Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnAdd.Click
Call EnabledControl()
Call ClearEntry()
End Sub

Save button event procedure:


Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnSave.Click
Call SaveRecord()
MessageBox.Show("Record Saved...")
Call DisabledControl()
End Sub

Edit button event procedure:


Private Sub btnEdit_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnEdit.Click
Call EnabledControl()
End Sub

Update button event procedure:


Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles btnUpdate.Click
With tbl
.Fields(1).Value = txt2.Text
.Fields(2).Value = txt3.Text
.Update()
Compiled by: Mr. Roel C. Traballo 111
JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

End With
MessageBox.Show("Record Updated...")
Call DisabledControl()
End Sub

Delete button event procedure:


Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles btnDelete.Click
Dim ans As Byte
ans = MessageBox.Show("Delete Record" & vbNewLine & "Are you
sure...", "Delete", MessageBoxButtons.YesNo,
MessageBoxIcon.Question)

If ans = DialogResult.Yes Then


tbl.Delete()
MsgBox("Record Deleted...")
tbl.MoveFirst()
Call DisplayRecord()
End If
End Sub

DisplayRecord Sub procedure:


Private Sub DisplayRecord()
With tbl
txt1.Text = .Fields(0).Value
txt2.Text = .Fields(1).Value
txt3.Text = .Fields(2).Value
End With
End Sub

ClearAll Sub procedure:


Private Sub ClearEntry()
txt1.Text = ""
txt2.Text = ""
txt3.Text = ""
txt1.Focus()
tbl.AddNew()
End Sub

SaveRecord Sub procedure:


Private Sub SaveRecord()
With tbl
.MoveLast()
.Fields(0).Value = txt1.Text
Compiled by: Mr. Roel C. Traballo 112
JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

.Fields(1).Value = txt2.Text
.Fields(2).Value = txt3.Text
.Update()
End With
End Sub

EnabledControl Sub procedure:


Private Sub EnabledControl()
txt1.Enabled = True
txt2.Enabled = True
txt3.Enabled = True
End Sub

DisabledControl Sub procedure:


Private Sub DisabledControl()
txt1.Enabled = False
txt2.Enabled = False
txt3.Enabled = False
End Sub

View Records button event procedure:


Private Sub btnView_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnView.Click
Dim objItem As ListViewItem
tbl.MoveFirst()
lvwRecord.Items.Clear()
Do While tbl.EOF = False
objItem = lvwRecord.Items.Add(tbl.Fields(0).Value)
With objItem
.SubItems.Add(tbl.Fields(1).Value)
.SubItems.Add(tbl.Fields(2).Value)
End With
tbl.MoveNext()
Loop
End Sub

End Class

Compiled by: Mr. Roel C. Traballo 113


JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Public Class Form1


Dim connect As New ADODB.Connection
Dim recordset As New ADODB.Recordset
Dim idnum As Integer

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) _


Handles MyBase.Load
Call ConnectDB()
recordset.MoveFirst()
Call DisplayRecord()
btnSave.Enabled = False
End Sub

Private Sub ConnectDB()


connect.Open("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\dbStudent.accdb")
recordset.Open("select * from tblStudent", connect,
ADODB.CursorTypeEnum.adOpenDynamic, _
ADODB.LockTypeEnum.adLockOptimistic)

End Sub

Private Sub DisplayRecord()


With recordset
txtID.Text = .Fields("studID").Value
txtName.Text = .Fields("studName").Value
dtpBDate.Text = .Fields("bdate").Value
If .Fields("sex").Value = "M" Then
rdoMale.Checked = True
Else
rdoFemale.Checked = True
End If
chkScholar.Checked = .Fields("scholar").Value

End With
End Sub
Private Sub SaveRecord()
With recordset
.AddNew()
'.MoveLast()
.Fields(0).Value = txtID.Text
.Fields(1).Value = txtName.Text
.Fields(2).Value = dtpBDate.Text
If rdoMale.Checked = True Then
.Fields(3).Value = "M"
Else
.Fields(3).Value = "F"
End If
.Fields(4).Value = chkScholar.Checked
.Update()
End With
End Sub

Private Sub SearchRecord()


With recordset
.MoveFirst()
.Find("studID='" & txtID.Text & "'")
If .EOF = True Then
MsgBox("no record found")
Call ClearEntries()
Compiled by: Mr. Roel C. Traballo 114
JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

Else
Call DisplayRecord()
End If

End With
End Sub
Private Sub ClearEntries()
txtID.Clear()
txtName.Clear()
dtpBDate.Text = ""
rdoFemale.Checked = False
rdoMale.Checked = False
chkScholar.Checked = False
txtID.Focus()
End Sub

Private Sub ACTION_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


_
Handles btnAdd.Click, btnSave.Click, btnSearch.Click, btnClear.Click,
btnShow.Click
If sender Is btnAdd Then
Call ClearEntries()
'recordset.AddNew()
recordset.MoveLast()
txtID.Text = recordset.Fields("studID").Value + 1
btnSave.Enabled = True
btnAdd.Enabled = False
End If

If sender Is btnSave Then


Call SaveRecord()
MsgBox("Record Saved...")
btnSave.Enabled = False
btnAdd.Enabled = True
End If

If sender Is btnClear Then


Call ClearEntries()
End If

If sender Is btnSearch Then


Call SearchRecord()

End If

If sender Is btnShow Then


Call ShowRecords()
End If
End Sub

Private Sub txtID_KeyDown(ByVal sender As Object, ByVal e As _


System.Windows.Forms.KeyEventArgs) Handles txtID.KeyDown
If e.KeyCode = Keys.Enter Then
Call SearchRecord()
End If
End Sub

Private Sub ShowRecords()


Dim items As ListViewItem
Compiled by: Mr. Roel C. Traballo 115
JOSE RIZAL UNIVERSITY
Compilation of Lectures and Laboratory Exercises using VISUAL BASIC.NET 2010

'Dim n As Integer

Do While recordset.EOF = False


items = Me.lvwRecords.Items.Add(recordset.Fields(0).Value)
With items.SubItems
.Add(recordset.Fields(1).Value)
.Add(recordset.Fields(2).Value)
.Add(DateDiff("YYYY", recordset.Fields(2).Value, Today))
End With
recordset.MoveNext()
Loop
End Sub
End Class

Compiled by: Mr. Roel C. Traballo 116

You might also like