You are on page 1of 54

Visual Programming: CSU_07310

Lecture 3
Variables and Calculations

Instructor: Mr. Bakiri A. Hussein

The Institute of Finance Management


Topics
•Variables and Data Types
•Performing Calculations
•Mixing Different Data Types
•Formatting Numbers and Dates
•Exception Handling
•The Load Event Procedure
•Debugging – Locating Logic Errors
Use TextBox Control to Get User Input

txtUserName
lblGreeting
btnClose
btnShowGreeting

Use the Text property of the TextBox to retrieve user input.


Syntax: nameOfTextBox.Text
Use the Clear method to clear TextBox
nameOfTextBox.Clear()
The Use of TextBox
•Use the Text property of the TextBox to retrieve user input.
Syntax: nameOfTextBox.Text

•Use the Clear method to clear TextBox


Syntax: nameOfTextBox.Clear()

•Display the contents of a TextBox with a Label


Syntax: nameOfLabel.Text = nameOfTextBox.Text

•Display a string with a TextBox


Syntax: nameOfTextBox.Text = StringValue
String Concatenation
Use the concatenation operator (&) to concatenate strings.

Examples:

lblGreeting.Text = "Hello " & txtUserName.Text

lblGreeting.Text = lblGreeting.Text & ". " & _


"How are you? "
The Focus Method
The controls that are capable of receiving some sort of
input, such as TextBox and Button, may have focus.

Syntax of Focus:

nameOfControl.Focus()

Example:

txtFirstName.Focus
Tab Order
The focus moves from one control to another when the user
presses the Tab key.

The order in which controls receive focus depends on the


value of the TabIndex property and TabStop property.

Only if the TabStop property is True can the control receive


focus.

The TabIndex can be set using the property window and the
View->Tab Order menu item.
Assigning Keyboard Access Keys to
Buttons
Windows applications almost always provide quick access
to buttons using Alt-<key> combination.

For example, the Exit button blow can be access using


Alt-x

To enable keyboard access to the Exit button, set the Text


property of the button as E&xit
Accept Buttons and Cancel Buttons
An accept button is clicked when the user presses the Enter
key.

A cancel button is clicked when the user presses the Esc key.

In the form’s property window, you may set the accept button
and the cancel button.
Variables and Data Types
•Variables are computer memory locations the application can
access while running.

•A variable can be used to


•Copy and store values entered by the user
•Perform arithmetic on numeric values
•Test values to determine that they meet some criterion
•Temporarily hold and manipulate the value of a control
property
•Remember information for later use in a program

•Every variable has a name, data type, scope, and lifetime.


Variable Names
Visual Basic program uses identifiers to name variables,
subprograms, classes and modules.

Rules of creating Visual Basic identifiers:

(1) The first character must be a letter or an underscore;


(2) Other characters, if any, must be the combination of a
letter, an underscore, or a digit.
(3) Maximum length of an identifier is 16383; however, the
recommended maximum length is 32.
(4) A Visual Basic reserved word cannot be used as an
identifier.
Naming Conventions
(1) Hungarian notation
Use the first three or more characters to represent the type and
the remaining characters to represent the purpose of the
identifier
Example:
intMax
(2) New notation that does not include the data type prefix, but
include the purpose of the identifier only. If the identifier is
formed using multiple words, make the first word lower case
and make the first letter of other word(s) capitalized. This is
called camel case.
Example:
firstName
Valid Identifier
_sum
strProduct
getSize
Item_222
MAX_HOURS

Invalid Identifier
13Users
get Size
box-22
IsEmpty?
Integer
Declaring a Variable
Syntax
[Dim | Private | Static] variablename As datatype [ =initialvalue]

Examples
Dim dblCarPayment As Double
Dim decItemPrice As Decimal

Dim blnIsDataOk As Boolean = True

Dim strStudentName As String


Dim intAge As Integer

Dim strName As String = String.Empty


Integer Data Types

 For values that will always be a whole number


 Usually name a variable starting with a 3 or 4 letter
prefix indicating the variable’s type

Data Naming Description


Type Prefix
Byte byt Unsigned integer from 0 to 255
Short shrt Signed integer from -32,768 to 32,767
Integer int Signed integer from -2,147,483,648 to 2,147,483,647
Long lng Signed integer from -9,223,372,036,854,775,808
to 9,223,372,036,854,775,807
Floating-Point Data Types

 For values that may have fractional parts


 Single used most frequently
 Double sometimes used in scientific calculations
 Decimal often used in financial calculations
Data Naming Description
Type Prefix
Single sng As large as 1038 plus or minus, 7 decimal positions
Double dbl As large as 10308 plus or minus,15 decimal positions
Decimal dec As large as 1029 plus or minus, 29 decimal positions
Other Common Data Types

• Boolean – variable naming prefix is bln


– Holds 2 possible values, True or False
• Char – variable naming prefix is chr
– Holds a single character
– Allows for characters from other languages
• String – variable naming prefix is str
– Holds a sequence of up to 2 billion characters
• Date – variable naming prefix is dat
– Can hold date and/or time information
Char Data Type
Variables of Char holds one Unicode character, which is a two-
byte character. Use quotation marks and c to denote a Char
literal.

Dim chrLetter As Char


chrLetter = " A " c

String Data Type


A variable of type String can refer to zero to about 2 billion
characters. Use quotation marks to create a string literal.

Dim strName As String


strName = " Jose Gonzalez "
Date Data Type
A variable of type Date can hold date and time information.
A date literal is defined using a pair of # signs.

Examples:

Dim dtmBirth As Date


dtmBirth = #5/1/2008#

Dim dtmStartTime As Date


dtmStartTime = #9/25/2008 7:00 PM#
The Object Data Type
If a variable is declared without data type, the Object data type
is assumed by the Visual Basic compiler. The prefix for a
variable of Object is obj, such objSender.

The Object type is the most flexible type, because a variable of


Object type can store different type of data at the runtime of the
program. For example, the same variable of Object type may
store number 20 first then refer to string "John" next.

The flexibility of the Object type comes with inefficiency and


more memory consumption.
Table of Literal Type Characters

Literal Type Data type Example


Character
S Short age = 35S
I Integer hours = 40I
L Long population = 20500L
D Decimal rate = 0.03D
F Single payRate =.03F
R Double sales = 2356R
C Char initial = "A"C
Assigning Data to an Existing Variable
Syntax
variablename = value

Examples
Dim intQtyOrdered As Integer
intQtyOrdered = 500

Dim strFirstName As String


strFirstName = "Mary"

Dim strZipCode As String


strZipCode = zipTextBox.Text

Dim decTaxRate As Decimal


decTaxRate = .05D
Performing Calculations
Two types of operators in Visual Basic: unary and binary.

A unary operator requires only one operand, such as

-5
-intCount
+4

A binary operator requires two operands, such as

5 + 10
intA + intB
Writing Arithmetic Expressions
Most commonly used arithmetic operators with their precedence.

Operator Operations Precedence


number
^ exponentiation (raises a number to a power) 1
- negation 2
*, / multiplication and division 3
\ integer division 4
Mod modulus arithmetic 5
+, - addition and subtraction 6

Parentheses are commonly used to override the order of


precedence. Parentheses have the highest precedence.
Operator Precedence Examples
The result is very different when the divide by 2 operation is
moved from the end of the calculation to the middle.

6 * 2^3 + 4 / 2 6 / 2 * 2^3 + 4

6* 8 +4/2 6/2 * 8 +4

48 +4/2 3 *8 +4

48 + 2 24 +4

50 28
Integer Division
The operator “\” performs integer division.

The decimal part of the quotient is discarded.

Example:

intHours = intMinutes \ 60

If intMinutes holds 100, intHours will hold 1 after the calculation.


Modulus
The modulus operator (MOD) performs integer division and
returns only the reminder.

Example:

intRemainder = 17 MOD 3

intRemainder will hold 2 after the calculation.


Exponentiation
To calculate a variable x taken to the power of y, use this
expression:

x^y

Example:

dblResult = 5.0 ^ 2.0 (mathematically, 52)


Getting the Current Date and Time
There are a few built-in functions available to get system date and
time.

Description Keyword Example


Date & Time Now datCurrent=Now
Time only TimeOfDay datCurrTime=TimeOfDay
Date only Today datCurrDate=Today

• Variables datCurrent, datCurrTime, and datCurrDate must be


declared as Date data types
Variable Scope
A variable’s scope refers to the part of a program where the
variable is accessible by programming statements.

1. Local Scope: A variable declared in a procedure has the


local scope. This variable can only be accessed in the
procedure where it is declared.

2. Class Scope: A variable declared inside a class but outside


of any procedures has the class scope. This class-level
variable can be accessed in any procedures of the class.
Variable Scope (Cont’d)
3. Global Scope: A variable declared outside of any class or
procedure has the global scope. This variable can be
accessed in any procedures.
Combined Assignment Operators

• Often need to change the value in a variable and assign the


result back to that variable
For example: var = var – 5
Subtracts 5 from the value stored in var
• Other examples:
x = x + 4 Adds 4 to x
x = x – 3 Subtracts 3 from x
x = x * 10 Multiplies x by 10
• VB provides for this common need with combined assignment
operators
Combined Assignment Operators
These special assignment operators provide an easy means to
perform these common operations:

Operator Usage Equivalent to Effect


+= x += 2 x = x + 2 Add to
-= x -= 5 x = x – 5 Subtract from
*= x *= 10 x = x * 10 Multiply by
/= x /= y x = x / y Divide by
\= x \= y x = x \ y Int Divide by
&= name &= last name = name & last Concatenate
Mixing Different Data Types
•Implicit Type Conversion
Ideally, the variables of the same type should be used in a
statement, e.g,

intSum = intA + intB 'All are integers

However, sometimes we may find it more convenient to


use variables of different types in a statement, e.g.,

dblSum = dblA + intB 'Only intB is integer

Visual Basic attempts to convert intB to Double before the


summation. This is called implicit conversion.
Mixing Different Data Types (Cont’d)
•Widening Conversions
With widening conversions, a type that takes less memory is
converted into a type that takes more memory. No loss of
precision occurs with widening conversions. Examples:
Dim dblVar As Double = 1234

•Narrowing Conversions
With narrowing conversions, a type that takes more memory is
converted into a type that takes less memory. Loss of precision
could occur with narrowing conversions. Examples:

Dim dblOne As Double = 1.2342376


Dim sngTwo As Single = dblOne 'sngTwo = 1.234238
Converting Strings to Numbers
Visual Basic will try to convert string values to numbers in
some cases.

Examples:

Dim sngTemperature As Single


sngTemperature = "12.13" 'Convert String into Single

Dim intCount As Integer


intCount = txtCount.Text 'Convert String into Integer
Option Strict
Implicit conversion is controlled by the setting of Option Strict.
If Option Strict On/Off is specified in the beginning of a file, the
setting affects the file. If the option is specified in the Project
property screen, the setting affects the project.

Option Strict On: Disable implicit narrowing conversion


Option Strict Off: Enable implicit narrowing conversion

When Option Strict On is in effect, the allowed implicit


conversions are from left to right:

Byte Integer Long Decimal Single Double


Type Conversion Errors
With Option Strict On, the statement below generates a
compilation error:

Dim intCount As Integer = "123"

With Option Strict Off, the statement below generates a


runtime error:

Dim intCount As Integer = "abc123"


Named Constants
A named constant is a symbol for a literal. The value of the
named constant cannot be changed while the application is
running.

Syntax
Const constantname [As datatype] = expression

Examples:
Const decPI As Decimal = 3.141593D

Const intMAXHOURS As Integer = 40

Private Const strCOTITLE As String = "ABC Company"


Explicit Type Conversion
When Option Explicit On is in effect, we must use some
functions to convert some conversions explicitly.

A function is a named, self-contained body of code, which


provide the output by manipulating the input.

Input(s) Function Output


Explicit Type Conversions
• The following narrowing conversions require
an explicit type conversion
– Double to Single
– Single to Integer
– Long to Integer
• Boolean, Date, Object, String, and numeric
types represent different sorts of values and
require conversion functions as well
Full List of Conversion Functions

• There are conversion functions for each data type

• CBool ( expr ) • CInt ( expr )


• CByte ( expr ) • CLng ( expr )
• CChar ( expr ) • CObj ( expr )
• CDate ( expr ) • CShort ( expr )
• CDbl ( expr ) • CSng ( expr )
• CDec ( expr ) • CStr ( expr )
Explicit Type Conversion Examples
• Rounding can be done with the CInt function
intCount = CInt(12.4) 'intCount value is 12
intCount = CInt(12.5) 'intCount value is 13
• CStr converts an integer value to a string
Dim strText as String = CStr(26)
• CDec converts a string to a decimal value
Dim decPay as Decimal = CDec(“$1,500”)
• CDate converts a string to a date
Dim datHired as Date = CDate(“05/10/2005”)
Invalid Conversions
• Conversion functions can fail
Dim dblSalary as Double = CDbl("xyz")
Dim datHired as Date = CDate("05/35/2005")
• String “xyz” can’t be converted to a number
• There’s no day 35 in the month of May

• These failed conversions


cause a runtime error called
an invalid cast exception
The Val Function
• The Val function is a more forgiving means of performing
string to numeric conversions

• Uses the form


Val(string) as
shown here

• If the initial characters form a numeric value, the Val function


will return that
• Otherwise, it will return a value of zero
The Val Function
Val Function Value Returned
– Val("34.90") 34.9
– Val("86abc") 86
– Val("$24.95") 0
– Val("3,789") 3
– Val("") 0
– Val("x29") 0
– Val("47%") 47
– Val("Geraldine") 0

Slide 3- 46
Specifying Decimal Positions
• Can add an integer to the format string to indicate number
of digits to display after the decimal point
• Rounding occurs when displaying fewer decimal positions
than the number contains as in the 2nd line

Number Value Format String ToString() Value


12.3 n3 12.300
12.348 n2 12.35
1234567.1 n 1,234,567.10
123456.0 f2 123456.00
.234 p 23.40 %
-1234567.8 c ($1,234,567.80)
Formatting Dates and Times

• The ToString method can format a Date or DateTime value


in a variety of ways
• If the date is 4/7/2008 and the time is 3:22:18 PM
Format String Description ToString() Value
d Short Date 4/7/2008
D Long Date Monday, April 7, 2008
t Short Time 3:22 PM
T Long Time 3:22:18 PM
F Full Date/Time Monday, April 7, 2008 3:22:18 PM

• Tutorial 3-8 provides an opportunity to work with number


formatting concepts
Message Boxes
• A message box is an easy way to notify the
user when an error occurs
• MessageBox.Show displays a pop-up
window with a message and an OK button
• There are two basic formats
MessageBox.Show( message )
MessageBox.Show( message, caption )
• message appears in the body of the window
• caption appears in the title bar of the window
Load Event Procedure

• Every form has a Load event procedure


• Automatically executed when the form is
displayed
• Double-click in any empty space on the form
• The code window will appear
• Place the code to be executed between the
Private Sub and End Sub lines
Debugging Problem

• The program runs but does not work correctly


(has one or more logic errors)
• Running the program with various inputs has
not isolated where those logic errors lie
• What can be done?
Visual Basic Debugging Aids
• You can set breakpoints
– A line or lines you select in your source code
– When execution reaches this line, it pauses
– You may then examine the values in variables and
certain control properties
– You may also single step through the program which
executes one statement at a time
• This allows you to see and examine:
– What is happening one statement at a time
– Where it is happening
– What the various data values are (Watches)
Visual Basic Debugging Aids

• Tutorial 3-12 demonstrates how to


– Set breakpoints
– Examine the values of variables and control
properties
– Use the Autos,
Locals, and
Watch windows
– Use the Debug Toolbar Step Into
Start Debugging Step Out

Break All Stop Debugging Step Over


Slide 3- 53
Next …..

• Decisions, Loops and Arrays


• ListBox, CheckBox, Radio buttons,Combo Box,
Progress bar and Timer.

Slide 3- 54

You might also like