CompilationLecLab VB 2010 .NET JRU
CompilationLecLab VB 2010 .NET JRU
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
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.
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
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
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.
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
Sample Output:
CODE WINDOW
Source Codes
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.
Press <F5>function key OR Start Debugging (F5) button from the Main Window
Use the same Solution and Project and add new form (Form2) to your project:
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.
End Class
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
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"
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.
End Class
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:
Format Function:
You can use the Format function to improve the appearance of the numbers displayed in
an interface.
- 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.
FormatNumber Function:
The FormatNumber function returns a formatted string representation for a number.
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)
The system time is the current time according to your computer systems clock.
Note: For these examples, assume that the system date is 11/15/06 and the system time is
4:30:44 PM
Use the same Solution and Project and add new form (Form3) to your project:
Sample Output:
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:
Modified codes: Date and Time Function (using Visual Basic .NET)
Public Class frmDateTime
Label4.Text = Today.ToString("dd")
'Label5.Text = Format(Now, "yyyy")
Label5.Text = Today.Year
End Sub
End Class
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.
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 - 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.
- Declares two Decimal variables named decPrice and decDiscount; the variables are
automatically initialized to 0
Dim mblnDataOk as Boolean
- 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.
- 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.
number1 = Me.TextBox1.Text
number2 = Me.TextBox2.Text
Me.Label1.Text = sum
Me.Label2.Text = difference
Me.Label3.Text = product
Me.Label4.Text = FormatNumber(quotient)
End Sub
End Class
Modified Codes
Me.TextBox1.Focus()
End Sub
Note:
Make necessary procedure/event on the
following buttons:
o +, , *, /, MOD & \
Clear button will clear all textboxes
Close button will close the application
Formula:
Note:
Remove the Minimize, Maximize & Close button
o In the properties window set:
ControlBox: FALSE
Set TextBox (Semestral Grade) to:
Enabled: FALSE
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
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)
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.
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.
Example #2: Displays a warning message box that contains the message Delete this record?
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.
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.
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.
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.
End Class
Example:
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
Logical Operators:
The logical operators, sometimes referred to as Boolean operators, allow you to combine
two or more conditions into one compound conditions
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
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
End If
End Sub
End Class
Note:
The data type specified in expression must match that of Case values.
Note:
Please note that grade is a string, so all the case values such as "A" are of String data
type.
Note
we use the keyword Is here to impose the conditions. This is generally used for numeric
data.
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
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
Try
FinGrd = CDbl(txtFinalGrade.Text)
Radio Buttons:
rdoBSIT
rdoBSCS
rdoBSCpE
Check Boxes:
chkCom
chkEng
chkFil
chkSci
chkMat
Buttons:
btnTestRdoBtn
btnTestChkBox
btnClearAll
Source Codes:
Private Sub btnTestRdoBtn_Click(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles btnTestRdoBtn.Click
End If
End Sub
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
Formula:
Semestral Grade = 25% of Prelim + 25% of
Midterm + 50% of Final
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.
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
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
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
End Sub
Try
GuessNum = CInt(txtNumber.Text)
GenRndNum = GenRnd.Next(1, 10)
End Try
txtNumber.Text = ""
txtNumber.Focus()
End Sub
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
Source codes:
Private Sub btnSpin_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnSpin.Click
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
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.)
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
Source Codes:
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
Specification:
GroupBox: (2)
ListBox
o Name: lstTerms
o Items: see items in the
figure
RichTextBox
o Name: rchMeaning
Source Codes:
Sample Output:
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:
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
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
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
lst1.ClearSelected()
lst2.Items.Clear()
End Sub
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
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%
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.
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
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.
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
Continuation
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
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
Continuation
Add new form to your existing solution / project
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
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.
MDI Child
Form
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
PictureBox Control
Sample Program:
Specifications:
PictureBox
o picBaby
Button
o btnShow
o btnHide
o btnEnable
o btnDisable
Source Codes:
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}
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.
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
Specifications:
ListBox
o lstNames
o lstScores
Button
o btnView
o btnClear
o btnExit
Label
o Label1, Label2, Label3
o lblAve
Specifications:
ComboBox
o cboMon
o cboDay
o cboYr
Specifications:
ListBox
o lstStud
Button
o btnShow
o btnSort
End Class
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.
<File> <Transaction>,
will display the Transaction Form (Form 3)
<File> <Exit>
will close the program
FORM 3: Transaction
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
Output:
For Cash Payment
Output:
For Charge Payment.
Then, will hide all controls under Total Amount and displays 5% Additional to all Charge
Payments (see example above)
FORM 4:
If button OK is clicked
will close the form window.
Appliance Store
ListView Control
Sample Program #1:
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
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:
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
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).
- 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
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.
Examples:
Ex. 1: Procedure that clears the contents of the textbox controls on the form
Ex. 2: Procedure that clears the contents of the textbox controls on the form using
Collection
Ex. 3:
Ex. 4:
intRegion1 = Val(txtRegion1.Text)
intRegion2 = Val(txtRegion2.Text)
sngBonus = Val(txtBonus.Text)
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)
Return expression
End Sub
Example:
Private Sub BonusButton_Click (ByVal sender As Object, ByVal e As _
System.EventArgs) Handles BonusButton.Click
intRegion1 = Val(txtRegion1.Text)
intRegion2 = Val(txtRegion2.Text)
sngBonus = CalcBonus(intRegion1, intRegion2, 0.05)
lblBonus.Text = Format(sngBonus, currency)
End Sub
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.
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:
Lock Type:
- Optional. Indicates the type of locks placed on records during editing.
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.
Primary Fields
Key
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
Click <Next>
Choose Your Data Connection: Click <New Connection> button
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)
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
Add Reference: Click <COM> tab and look for <Microsoft ActiveX Data Objects 6.0 Library>
FORM LAYOUT:
SOURCE CODES:
Public Class Form2
Dim db As New ADODB.Connection
Dim tbl As New ADODB.Recordset
tbl.MoveFirst()
Call DisplayRecord()
End Sub
-----------------
End With
End Sub
-----------------
With tbl
.MoveFirst()
Control/Objects name:
TextBox Buttons
txt1 btnNext, btnPrev,
txt2 btnFind, btnEdit,
txt3 btnFirst, btnLast,
btnAdd, btnSave,
btnDelete,
btnView
ListView
lvwRecord
Source Codes:
Object declarations:
Public Class Form1
Public db As New ADODB.Connection
Public tbl As New ADODB.Recordset
Call DisplayRecord()
Call DisabledControl()
End Sub
With tbl
.MoveFirst()
.Find("num='" & n & "'")
If .EOF = True Then
MsgBox("Student number not found")
Else
Call DisplayRecord()
End If
End With
End Sub
End With
MessageBox.Show("Record Updated...")
Call DisabledControl()
End Sub
.Fields(1).Value = txt2.Text
.Fields(2).Value = txt3.Text
.Update()
End With
End Sub
End Class
End Sub
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
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
End If
'Dim n As Integer