Chapter 3
Chapter 3
Chapter 3
Chapter 3
Visual Basic.Net Fundamentals
As you see in the previous chapters, a Visual Basic.Net application is made of a group
of forms and modules. Each form is a class and has its own controls. Each control has a
number of events that are encountered during the interaction between users and the
program. An event is often responded by a procedure that tells what to do for the event.
This chapter discusses the contents of event procedures.
3.1
Statement
Statement
Statement
Statement
It begins with Private Sub and ends with End Sub. It has a set of VB.Net statements
that respond to an event (defined by the EventName) of an control (defined by the
ControlName). When this event procedure is trigged to run, the statements will be
executed one by one from top to bottom. The first statement will be called for
execution. After the first statement, the second statement will be called and executed.
The procedure keeps the same pattern for execution until it reaches to End Sub.
Take the below event procedure as an example:
Private Sub Calculate_Click (ByVal sender As System.Object, _
ByVal e As System.EventArgs)
_
Handles Calculate.Click
REM This is a comment statement
REM Below are variables a, b, c, rt1, rt2 and
REM chk declared within this procedure
Dim
Dim
Dim
Dim
Dim
Dim
Dim
a as integer
b as integer
c as integer
rt1 as Double
rt2 as Double
chk as Long
Response as integer
30
Chapter 3
0 then
31
Chapter 3
This event procedure responds to the Click event of the control called Calculate.
3.2
VB.Net Statements
In this section we will discuss the comment statement, the Dim statements, the
assignment statements, and the if-Then-Else-End If statement used to find roots for a
quadratic equation. Discussion of other VB.Net statements will be provided in later
chapters.
3.2.1
Comment Statements
Comment statements are the statements that start with a single quotation mark () or
REM. They help explain the logic of the code. Since they are not executable statements,
they will be skipped during the execution of the event procedure.
3.2.2
Dim Statements
The Dim statement declares a room in the computer memory with a name. Its syntax
is as follows:
Dim
In this syntax, <variable> is a placeholder for the name of a room. A room contains a
group of memory cells allocated to store various values. The words Dim and As are the
keywords reserved for VB.Net applications.
How big is the room represented by a variable? Dim statements use data type to
define the size of the room. When a variable is declared to be of Integer data type, the
room for the variable is sized with two bytes.
Table 3-1 lists a group of data types commonly used in VB.Net. The Long Integer data
type takes 4 bytes to size variables that store whole numbers without any factional
portion. The Single and Double data types take 4 and 8 bytes respectively to represent
float numbers. The Currency or Date data type specifies the values of a variable in the
format of currency or date. The String data type specifies a variable to have a string of
characters. The Boolean data type takes 2 bytes to store values either TRUE or
FALSE. The Object data type is a compounded data type. We will discuss this data
type when we use it in later chapters.
32
Chapter 3
Description
Byte
Integer
Long
Single
Double
Currency
String
Boolean
Date
Object
Range
0 to 255.
32,768 to 32,767.
2,147,483,648 to
2,147,483,647.
3.402823E38 to
1.401298E 45 (negative
values).
1.401298E 45 to
3.402823E38 (positive
values).
1.79769313486231E308 to
4.94065645841247E 324
(negative values).
4.94065645841247E 324 to
1.79769313486231E308
(positive values).
8-byte number with a 922,337,203,685,477.5808
fixed decimal point to
922,337,203,685,477.5807.
String of characters Zero to approximately two
billion characters.
TRUE or FALSE
2 bytes
8-byte date/time
January 1, 100 to December
value
31, 9999.
4 bytes
Any object reference.
StudentName As String
Tuition As Currency
StudentAddress As String, StudentID As Long
a, b, c as Integer
The first statement declares the variable StudentName. Its data type is String. The
second statement declares the variable Tuition. It has the Currency data type. The
third statement combines multiple declarations in one line and separates them by
commas. The last statement defines three variables. The first two variables a and b are
specified as the Object data type. The last variable c is specified as the Integer data
type.
A variable is often named to reflect its use. When you declare a variable to store a
value for the parameter A of a quadratic equation, it is suggested to name it as
ParameterA, a, or CoefficientA. The variable name cannot begin with a numeric letter.
You cannot name a variable as 123ABC. Additionally, two identical variable names
33
Chapter 3
cannot be used in a form. Otherwise, you may run into errors when you execute the
form. Also variable names cannot be the same as control names.
3.2.3
Assignment Statements
Note that the control property or variable being assigned a value always appears on the
left side of the = sign. One and only one control property or variable can be placed on
the right side of the = sign and is assigned by a value.
Example assignment statements are listed below:
A = 4
B = A
C = val(val_c.text) + A + B
Root1.text = rt1
The first assignment statement assigns 4 to variable A. The format of this assignment
statement is:
Variable = value
The second assignment statement assigns the current value of variable A to variable B.
Before this statement is executed, variable A must have a value. Otherwise running
errors will occur. The format of the statement is:
Variable = variable
The third assignment statement assigns the value computed from the expression Val
(val_c.Text) + A + B to variable C. Its format is:
Variable = expression
Note that the expression is made of the text property of the textbox control val_c,
variables A and B.
The fourth statement assigns the current value of variable rt1 to the text property of the
textbox control root1.
34
Chapter 3
Note that on the right side there are values, variables, expressions, properties or
combination of them. On the left side there are one and only one variable or a control
property. You cannot find a valid assignment statement as shown below:
X+Y = A + B
The above statement has two variables combined on the left side of the = sign and
violates the definition of the assignment statement.
3.2.3.1 Dot Notion
A dot notion is used to link a property to a control. The general format of the dot
notion is Object.Property. A control is considered an object in VB.Net. The above
format for a control is then shown as Control.Property. For example, Root1.text
indicates the text property of the control Root1.
3.2.3.2 Expression
An expression defined in VB.Net is a combination of two or more variables, control
properties and/or constants with operators. It is the VB.Net implementation of a
mathematical expression in algebra. To understand the definition of an expression in
VB.Net, we need to discuss three key terms: constants, operators, and functions.
Constants
Constants are values that do not change within a VB.Net application. Numbers and
strings are constants. For example, 100 and 3.1415926 are the number constants, while
Real roots do not exist and Please enter parameter a are the string constants.
VB.Net allows the use of symbolic constants (or named constants) for actual numbers
or strings. Assigning a name to a constant follows the below syntax:
CONST <Constant-Name> AS <Data-Type> =
<Value> or <Expression>
For example,
CONST PI as Single = 3.1215926
CONST Year as INTEGER = 365
In the above examples, the CONST and AS are the keywords reserved in VB.Net. The
<Constant-Name>, <Data-Type>, <Value>, and <Expression> are the placeholders.
You can use any name for a constant as long as the name follows the VB.Net naming
convention. Data types used here are the same as those in Dim statements. The value
can be a string constant, a number or an expression.
35
Chapter 3
Operators
Operators are symbols used for carrying out mathematical operations. There are four
types of operators in a VB.Net expression: arithmetic, concatenation, comparison, and
logical.
1)
Arithmetic Operators
Arithmetic operations are listed in Table 3-2. They are used for arithmetic calculations.
Note that all of these operators are the same as those in algebra. You should be able to
handle them easily.
Table 3-2
Operator
Arithmetic Operators
Example
( )
^
(a+b+c)
Radius ^2
4* A
/
\
Tuition/4
Number\7
Mod
Days mod 7
+
-
a+b+c
a-b
Description
Group operating elements.
Get exponential value of
Radius
Multiply 4 by the value
stored in variable A
Divide tuition by 4
Perform
an
integer
division of number by 7
Get reminder from dividing
days by 2
Sum a, b and c together
Subtract b from a
Here we just review the integer division and mod operations. The integer division
rounds divisor and dividend to integers before the division operation is executed.
Further the quotient is truncated to an integer. For example,
A
B
C
D
=
=
=
=
4.1415926
13.345
B\A
B mod A
The B\A operation will first round the value in A to be 4 and value in B to be 13, then
perform the division of 13 by 4, get the result to be 3.25, and truncate the result to be 3.
Finally the variable C is assigned with 3.
36
Chapter 3
The mod operation finds the integer reminder that results from the integer division of
two operands. Given the above example, the B mod A operation will yield a value of 3
with reminder of 1. Therefore the variable D is assigned with 1.
Operations in an expression follow the below order (or the same order as in algebra):
1)
2)
3)
4)
5)
6)
Parenthesis
Exponentiation
Multiplication or division
Integer division
Modulus
Addition or subtraction
In case there are elements in the same execution level, the order will be from left to
right.
2)
Concatenating Operators
Concatenating operators are string operators because they are applied only to string
constants and string variables. There are two string operators available in VB.Net: +
and &. They both append the second string value to the first one. For example,
Dim
Dim
Dim
A =
B =
A as String
B as String
C as string
Please enter
a value for the program
C = A & B
D = A + B
E = C + , OK?
The string variable A is assigned with a string constant Please enter , while the
variable B is assigned with a constant a value for the program. The C and D
variables will get the same result as Please enter a value for the program.
even with two different string operations. The last statement shows the concatenation
operation of a string variable and a constant string , Ok?
3)
There are six comparison operators used in VB.Net for comparison of any two
variables, constants, expressions or control properties. Table 3-3 lists these six
operators.
37
Chapter 3
Comparison operators in VB.Net are the same as those in mathematics. However there
are several issues programmers should be aware of. First, the symbols for the greater
than or equal to and less than or equal to operators are >= and <= respectively,
different from and in mathematics. In addition, the not equal to operator is
symbolized as <> instead of . Second, when variables, constants, expressions, or
control properties are compared using the above operators, they should be with the
same data type. You cannot compare a string value with a numerical value. Third, the
result of comparison is a Boolean value, that is, either TRUE or FALSE.
Using comparison operations, we can form simple logical conditions as shown in Table
3-3.
Table 3-3 List of Comparison Operators
Operator
=
>
>=
<
<=
<>
4)
Example
StudentID = 1567001
Score > 90
Score >= 90
Score < 60
Score <= 60
Score <> 100
Description
Equal to
Grater than
Grater than or equal to
Less than
Less than or equal to
Not equal to
Logical Operators
Simple logical conditions can be combined to form a compound logical condition using
logical operators And, Or, Not, and Xor (see Table 3-4). Using the And operator we
can represent the mathematical expression 15 < y < 100 by two simple logical
conditions 15 < y and y < 100.
Table 3-4 List of Logical Operations
Operator
And
Or
Not
Xor
Example
Description
38
Chapter 3
Functions
A VB.Net function is an operation that takes one or more arguments and returns a
single value. Its syntax is as follows:
Function_Name (arg1, arg2, ., argn)
' Returns 2.
returns based on a, b, and c
Val() Function
Val () function converts alphabetical numbers in a string to a numeric value. Its syntax
is Val(string). The string argument is any valid string expression. Examples of Val()
function are as follows:
Dim aValue as Integer
aValue = Val("24571")
aValue = Val(" 2 45 7 1")
aValue = Val("25 and 571")
aValue = Val(" + 2 45 7 1")
aValue = Val(" - 25 and 571")
'
'
'
'
'
Returns
Returns
Returns
Returns
Returns
24571.
24571.
25.
+24571.
-25.
Val() function stops reading the string when it cannot recognize a character as part of a
number. Symbols and characters that are often considered parts of a numeric value in
math, such as dollar signs and commas, are not recognized as part of a numerical value
in VB.Net. Blanks, tabs, and linefeed characters are skipped from the argument.
The following Val () function returns the value of 3801:
Val("
39
Chapter 3
In addition, Val() function recognizes only the first period (.) as a valid decimal
separator.
Very often we use Val() function to convert a value of the text property from a string to
a number, which is then assigned to a numeric variable. Take the below statements as
an example,
A = val(val_a.text)
B = val(val_b.text)
C = val(val_c.text)
The first statement uses the Val() function to convert the user input (which is a string)
into a numeric value and assigns the value to variable A. The second and third
statements convert user inputs in the textbox controls into numerical values and assign
them to variables B and C, respectively.
MsgBox() Function
Msgbox () function displays a message in a dialog box, waits for the user to click a
button, and returns an Integer indicating which button is clicked by the user. Its syntax
is
MsgBox(prompt [, buttons] [, title])
Buttons
Title
Optional. It is a string expression that will appear in the title bar of the
dialog box. The application name is placed in the title bar when this
argument is omitted.
40
Chapter 3
Value
vbOKOnly
vbOKCancel
vbAbortRetryIgnore
0
1
2
vbYesNoCancel
vbYesNo
vbRetryCancel
vbCritical
vbApplicationModal
3
4
5
16
0
vbSystemModal
4096
Description
Display OK button only.
Display OK and Cancel buttons.
Display Abort, Retry, and Ignore
buttons.
Display Yes, No, and Cancel buttons.
Display Yes and No buttons.
Display Retry and Cancel buttons.
Display Critical Message icon.
Application modal; the user must
respond to the message box before
continuing work in the current
application.
System modal; all applications are
suspended until the user responds to
the message box.
The Return Values can be one of the values in the list below:
Constant
Value
Description
vbOK
vbCancel
vbAbort
vbRetry
vbIgnore
vbYes
vbNo
1
2
3
4
5
6
7
OK
Cancel
Abort
Retry
Ignore
Yes
No
41
Chapter 3
The MsgBox() function asks the user to respond by clicking on the Yes or No button
(see Figure 3-1). If the user clicks the Yes button, the value of 6 (or VbYes) will be
returned and assigned to the variable response. The next statement will check if the
return value is VBYes. If it is VBYes, then the program executes the Exit Sub statement
and exits the procedure.
Str() Function
Str () function returns a String value converted from a number. Its syntax is
Str(number). The number argument is a Long-type argument containing any valid
numeric expression. Below are examples that use the Str() function to return a string
representation of a number.
Dim MyString as string
MyString = Str(4591)
MyString = Str(-4591.65)
MyString = Str(4591.001)
When numbers are converted to strings, a leading space is always reserved for the sign
of number. If number is positive, the returned string contains a leading space and the
plus sign is implied. The Str() function is just the reverse operation of Val() function.
InStr() Function
It returns a Long-type value that specifies the position of the first occurrence of one
string within another. Its syntax is InStr([Start, ] String1, String2)
The InStr () function syntax has these arguments:
Start
String1
42
Chapter 3
String2
Below are examples that show the use of the InStr() function to get the position of the
first occurrence of one string within another.
Dim SearchSource as String, SearchKey as String
Dim Position as Integer
SearchSource = "Civil Engineering Program is a Nice Program"
SearchKey = "Program"
' Search starts at position 5. Returns 19.
Position = Instr(5, SearchSource, SearchKey)
' Search starts at position 20. Returns 37.
Position = Instr(20, SearchSource, SearchKey)
The InStr() function is useful for extracting a subset of a string. Suppose you have a
form with a textbox control. The user can input a quadratic expression such as
10005x^2 2222x +1 into the textbox control. You can use the following InStr()
function to check where the string x^2 starts.
Position = instr(val_a.text, x^2)
Note that the val_a is the name of the textbox control. A string x^2 is the search key.
The position will be assigned with 6 for the above example.
Mid() Function
It returns a String value that contains a specified number of characters from a string. Its
syntax is Mid(String, Star t[, Length]). It has three arguments listed below:
String
Start
Length
Optional.
It specifies the number of characters to be extracted out
of String. If it is omitted, all characters from the Start position to the end
of the string are returned. Also if the number of characters in String
(including the character at Start) is less than the Length value, all the
characters after the Start position (including the Start character) is
returned.
43
Chapter 3
The below example uses the Mid () function to return a specified number of characters
from a string.
Dim
Dim
Dim
Dim
Astring as String
FirstString as String
LastString as String
MidString as String
= Mid(AString, 7)
The second example uses both the InStr() and Mid() functions to extract parameter a
from a textbox that stores a quadratic equation expression.
In this example, the quadratic expression is stored in the text property of the textbox
control func. The extracted value is then sent to the text property of the textbox val_a.
3.2.4
If-Then-Else statement is a compound VB.Net statement that controls the flow of the
program'
s execution. Normally a program'
s logic is to flow through statements from left
to right, and from top to bottom. When an If-Then-Else statement is used, it
conditionally executes a group of statements depending on the value of a logical
expression.
44
Chapter 3
Else
VB.Net Statements 2
End If
When the logical expression is True, then the VB.Net statements 1 will be executed.
Otherwise, the VB.Net statements 2 will be executed. In detail, the execution flow can
be described by a flow chat in Figure 3-2.
Logical
Expression
False
True
VB.Net
Statements 1
VB.Net
Statements 2
When no VB.Net statements 2 are used in the Else part, the If-Then-Else statement will
become an If-Then statement. Its syntax is as follows:
If Logical Expression Then
VB.Net Statements 1
End If
45
Chapter 3
This example shows that the logical expression is chk < 0, where variable chk is
assigned a value before the execution of the logical expression. If the expression returns
True, the following two statements will be executed.
MessageBox.Show (No real roots exist)
Exit Sub
Chk < 0
True
MessageBox.Show()
Exit Sub
False
Rt1 = (-b+Math.sqrt(chk))/(2*a)
Rt2 = (-b-Math.sqrt(chk))/(2*a)
46
Chapter 3
The flow chart for the above example is shown in Figure 3-4.
A<0
True
False
A = A + 1
C = B + A
C = C + B
You can use the single-line form to have multiple statements executed when the logical
expression is True. All statements must be on the same line and separated by colons, as
in the following statement:
If A > 0 Then A = A + 1 : C = B + A : C = C + B
47
Chapter 3
For example,
If chk <
0 then
Response = Msgbox (
Else
Rt1 = (-b+Math.sqrt(chk))/(2*a)
Rt2 = (-b-Math.sqrt(chk))/(2*a)
End If
The below VB.Net statement is embedded inside the outer If-Then-Else statement:
If response = vbYes then
Exit Sub
End if
3.3
Q1.
Questions
Determine the data type for each of the following variables:
Variable
Variable
Variable
Variable
Variable
expected
expected
expected
expected
expected
to
to
to
to
to
store
store
store
store
store
Q2.
Q3.
Note that Exp(x) and Abs(x) are the VB.Net functions that calculate the
exponential and absolute values of x, respectively. Also note that Sin(x),
Cos(x), Exp(x), Sqrt(x), and Abs(x) are the mathematical functions. Therefore,
each of them is prefixed with Math in VB.Net applications.
48
Chapter 3
Q4.
Q5.
Q6.
true As Integer
variable as Long
123Lotus as String
a,b,c as Integers
_
_
_
a as integer
b as integer
c as integer
rt1 as Doubl
rt2 as Double
chk as Long
response as integer
0 then
49
Chapter 3
Root1.text = str(rt1)
Root2.text = str(rt2)
End Sub
Q7.
You need to design a graphic user interface that allows users to enter the value
for t, calculate the y value and display the y value on the interface. A user
should be able to clear the t and y values anytime and terminate the program
when the user clicks on the Cancel button. [Hint: Go to VB.Net online help to
search functions for e t and log 10 (t ) .
Q8.
a_box
Roots
Control Names:
B b_box
C c_box
root1
root2
Roots
Cancel
50
Chapter 3
_
_
_
Check as Double
A_val, b_val, c_val as double
Temp1, Temp2 as double
Root1_val, root2_val as double
A_val = val(a_box.Text)
B_val = val(b_box.Text)
C_val = val(C_box.Text)
Check =
Q9.
Q10.
Q11.
Q12.
51
Chapter 3
Q13.
The below chart shows the execution flow that determines the roots of a
quadratic equation: ax^2+bx+c = 0. If parameter a does not exists, enter 0 in its
textbox. Follow the same rule for parameters b and c.
Start
True
False
A=0
Root1 = -B/C
End
B=0
True
Root1 = sqrt(-c/a)
Root2 = -sqrt(-c/a)
End
False
True
C=0
False
Root1 = 0
Root2 = -sqrt(-b/a)
End
B^2-4ac <= 0
False
True
Root1 = (-b +sqrt(b^2-4ac))/(2a)
Root2 = (-b sqrt(b^2-4ac))/(2a)
End
End
52