introduction to vb programming

51
Introduction to VB Programming Chapter 3 03/14/2022 VBN2008-03 1

Upload: leandra-knapp

Post on 31-Dec-2015

30 views

Category:

Documents


4 download

DESCRIPTION

Introduction to VB Programming. Chapter 3. Quotes for Today. When faced with a decision, I always ask, “What would be the most fun?” Peggy Walker It is a capital mistake to theorize before one has data. Arthur Conan Doyle. Creating a Project With Code. A Simple Program. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Introduction to VB Programming

04/19/2023 VBN2008-03 1

Introduction to VB Programming

Chapter 3

Page 2: Introduction to VB Programming

Quotes for Today

When faced with a decision, I always ask, “What would be the most fun?”

Peggy Walker

It is a capital mistake to theorize before one has data.

Arthur Conan Doyle

04/19/2023 VBN2008-03 2

Page 3: Introduction to VB Programming

Creating a Project With Code

A Simple Program

04/19/2023 VBN2008-03 3

Page 4: Introduction to VB Programming

Two Types of Applications(2 of the many)

• Windows Applications– Access Windows environment

• Console Applications– Access DOS environment

04/19/2023 VBN2008-03 4

Page 5: Introduction to VB Programming

Anatomy of a Simple Program

04/19/2023 VBN2008-03 5

‘ Welcome1.vb‘ Simple Visual Basic programModule modFirstWelcome

Sub Main() ‘entry point of program‘() indicates a procedure

Console.WriteLine(“Welcome to Visual Basic!”)End Sub ‘Ends Main Procedure

End Module ‘Ends modFirstWelcome

Keywords

Identifiers

Green = Comments

Class Method String

Page 6: Introduction to VB Programming

A Module

• Collectively called a module definition

• Console modules consist of logical groupings of procedures – simplify program organization

• Convention:– Begin all modules with “mod”

• Example: modWelcome– Not case sensitive

04/19/2023 VBN2008-03 6

Page 7: Introduction to VB Programming

An Identifier

• A series of characters – Consist of letters, digits & underscores (_)– Not case sensitive

• Cannot– Begin with a digit– Contain spaces

• Examples– Valid: modFirstWelcome, num1, SalesTax– Invalid: 123xyz, My Tax, 753 Room

04/19/2023 VBN2008-03 7

Primitive Data Types:Boolean Byte CharDate Decimal DoubleInteger Long SbyteShort Single StringUinteger Ulong UShort

Page 8: Introduction to VB Programming

A Keyword (Reserved Word)

• A particular word that has a specific meaning within each programming language

• Examples:– Module, End, Sub, If, For, Loop– For more examples refer to Pages 76 – Not case sensitive, but VB will

automatically convert to “proper” case

04/19/2023 VBN2008-03 8

Page 9: Introduction to VB Programming

Keywords (or Reserved Words)

• Do not try to use these words as variable names.– Misspelling a keyword may cause a

syntax error – VB will assume you are creating a new

identifier.– But…the program will not work correctly.

04/19/2023 VBN2008-03 9

Page 10: Introduction to VB Programming

Spacing (Whitespace)

• VB ignores spaces and tabs between identifiers– Vertically and horizontally

• Use vertical blank lines, tabs and horizontal spaces to make projects easier to read.

04/19/2023 VBN2008-03 10

Page 11: Introduction to VB Programming

Statements

• Console.WriteLine(“Hi!”)– (“Hi”) is the argument

• Note the dot notation…– Classes organize groups of related

methods• WriteLine is the method• Console is the class to which the method

belongs

04/19/2023 VBN2008-03 11

Page 12: Introduction to VB Programming

The Simple Program Revised

• Pg 78;– File>New Project>Console Application– Name = WelcomeConsole– Program Name = Welcome1.vb– Reserved words are blue, text is black– Change name of Module to ModWelcome– Writing code– Run program

• Tools>Options personalizes environment

04/19/2023 VBN2008-03 12

Page 13: Introduction to VB Programming

Features

• IntelliSense – When the dot (.) is keyed after Console, a list of

available methods is displayed– Options

• List Members – lists the members of an object.• Parameter Info – Lists the members of an object.• Quick Info – displays information in tool tips as the

mouse rests on elements in your code.• Complete Word – completes typed words• Automatic Brace Matching – adds parentheses or

braces as needed.

04/19/2023 VBN2008-03 13

Page 14: Introduction to VB Programming

Documenting Code

Commenting…

04/19/2023 VBN2008-03 14

Page 15: Introduction to VB Programming

Consistency, Consistency!

• Just as important as commenting code

• Reduces reader frustration• Makes comments & code

– easier to understand• Makes debugging

– easier – faster

04/19/2023 VBN2008-03 15

Page 16: Introduction to VB Programming

Commenting Code

• Used to identify the purpose of a piece of code, the author, creation date, requirements– Required in this class!

• Indicator is the apostrophe.– Ex. ‘This is a comment.

• The default color for VB is green.– Note: for those of you who might be colorblind

to green, the comment color property can be changed within the environment controls. But…Don’t do it in here or in the Lab…

04/19/2023 VBN2008-03 16

Page 17: Introduction to VB Programming

Comments

• Explains – what is going on or – what is being described

• Denoted by a single quotation mark (‘)

• Example‘Input variable

Dim Principal As Single ‘The original loan amount

Dim Address As String ‘Shipping address for client

04/19/2023 VBN2008-03 17

Page 18: Introduction to VB Programming

Comment Levels

• Application Level– Name - name of application– Author/Company - who created it– Add-ins - are there any other modules or

code objects necessary to run this program– Purpose of Program - what is the program

supposed to do?– System Requirements - what is the system

upon which this program will operate

04/19/2023 VBN2008-03 18

Page 19: Introduction to VB Programming

Comment Levels

• Module Level– Necessary when multiple programmers

are working on a project.– Useful when planning to reuse the code.– Same parameters as before, but with

addition of • Dependencies –

– declares what is required as input for the module to work (Passing parameters)

04/19/2023 VBN2008-03 19

Page 20: Introduction to VB Programming

Comment Levels

• Procedure Level– Used to describe to programmers what

the procedure does and how it does it.– Used for user-defined and non-obvious

procedures and functions.• Ex. A new form of the Square Root function

– Helps during a multi-programmer project • Lets other programmers know who to

contact when there are questions or problems with the code.

04/19/2023 VBN2008-03 20

Page 21: Introduction to VB Programming

Comment Levels

• Code Level– To specify what a piece code is doing– To specify that a piece of code needs further

attention– Use these as suggestions for consistency

– ‘ Generic comment - explanation

– ‘??? Questionable code - useful for debugging

– ‘!!! Code requires attention - useful for reminders or where to provide additional work.

– ‘-MLM- Include your initials for comment referencing

04/19/2023 VBN2008-03 21

Page 22: Introduction to VB Programming

Comment, Comment, Comment!

• Provides– meaning to code– additional information to other

programmers– reasons why one method was used over

another for future maintenance

• Makes Maintenance EASIER!

04/19/2023 VBN2008-03 22

Page 23: Introduction to VB Programming

Console.WriteLine Revisited

• Dim number1 as Integer• Number1 = Console.ReadLine()

– ReadLine() is a method that causes the program to pause and wait for user input.

– After the value is entered by keyboard, the user presses the Enter key to send the value to the program.

• Example:Console.WriteLine(“The sum is ” & sumofNumbers)

04/19/2023 VBN2008-03 23

Page 24: Introduction to VB Programming

Basic Components of VB

04/19/2023 VBN2008-03 24

Variables &Assignment Statements

Page 25: Introduction to VB Programming

Variables

• A Variable– Is a temporary storage location for

information– Clears upon exit of either the program

or the procedure– Examples:

• Sum SalesTax SquareRoot• Count Sales_Tax Principal

04/19/2023 VBN2008-03 25

Page 26: Introduction to VB Programming

Variable Declarations

• Name of a variable is any valid identifier– Cannot be keywords– Maximum length is 255 characters– Must begin with a letter– Must contain only letters, numbers and

underscores.– VB is not case sensitive so

• uppercase and lowercase letters are treated in the same way.

• Variable’s Type - what type of information each variable may contain.

04/19/2023 VBN2008-03 26

Page 27: Introduction to VB Programming

Variable Declarations

• Declaration of Variables– Provides the Variable Name and its data

type– Ex. Dim sum As Integer

– VB always initializes variables to Zero for numbers and the Null set for characters and strings

04/19/2023 VBN2008-03 27

Variable Identifier

Variable’s Data Type

Page 28: Introduction to VB Programming

Variable Data Types

04/19/2023 VBN2008-03 28

Data Type

.NET Runtime

Type "System."

Storage Size Purpose

Boolean Boolean 2 bytes True or False

Char Char 2 bytes 0 to 65535String String depends 0 to approx 2 billion Unicode characters

Date DateTime 8 bytes January 1, 0001 to December 31, 9999

Byte Byte 1 byte 0 to 255 (unsigned)SByte SByte 1 byte -128 to 127Integer Int32 4 bytes -2,147,483,648 to 2, 147,483,647

Long Int64 8 bytes -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807UShort UInt16 2 bytes 0 to 65,535, inclusive

UInteger UInt32 4 bytesA numeric variable, holds values in range -2147483648 to 2147483647

ULong Int64 8 bytes 0 to 18,446,744,073,709,551,615 (unsigned)

Object Object 4 bytes Any type can be stored in a variable of type Object

Single Single 4 bytes-3.402823E38 to -1.41298E-45 for negative #'s & 1.401298E-45 to 3.402823E38 for positive #'s

Double Double 8 bytes A floating point numeric variable even bigger than Single

Decimal Decimal 16 bytes+/- 79228162514264337593543950335 w/no decimal+/7.9228162514264337593543950335 w/28 decimal places

User-defined ValueType depends more about these later

Page 29: Introduction to VB Programming

Variable Declarations Changes from VB6 to

VB.Net• New data types

– Char– Unsigned Integers

• Ulong - 8 bytes• Uinteger - 4 bytes• Ushort - 2 bytes• Sbyte - 1 byte

• Lost data types– Currency– Variant – A great

thing!– Image (use

PictureBox instead)

04/19/2023 VBN2008-03 29

Note about Unsigned Integers - They are non-CLS compliant and not supported by all .Net languages

--Avoid using--

Page 30: Introduction to VB Programming

More Changes from VB6 to VB.Net

• Replacements– RadioButtons replaces OptionButton– GroupBox replaces Frame– SelectedIndex in ListBox replaces

ListIndex – Images are added to PictureBox’s by

using the System.Drawing.Image.FromFile method

04/19/2023 VBN2008-03 30

Page 31: Introduction to VB Programming

Variable Declarations

• Declarations made – in the General Declaration Section are

available throughout the entire program.• This is Global Scope.

– inside a procedure are available only within the procedure• This is Local Scope.

• Both will be discussed in more detail later.

04/19/2023 VBN2008-03 31

Page 32: Introduction to VB Programming

Assignment Statements

• Assigns a value, variable or expression to a variable– Syntax: VariableName = value or variable or expression

– A variable is placed on the left of the equal sign (=)• Think of the “=” as “takes on the value of”

– The value to be stored in the variable appears on the right.• The value is made up of the following:

– A value– An expression– A variable (Identifier)

– Ex. sum = count + 3

04/19/2023 VBN2008-03 32

Page 33: Introduction to VB Programming

Assignment Statements

– When a value is stored in a variable (on the left side of the assignment operator), it replaces the existing data. • This is known as destructive read-in.

– Ex. sum = 3 + 5

– When a variable is used (on the right side of the assignment operator), the value stored in the variable is preserved. • This is known as nondestructive read-in.

– Ex. sum = count + 1

04/19/2023 VBN2008-03 33

Page 34: Introduction to VB Programming

Arithmetic in VB

And Operator Precedence

04/19/2023 VBN2008-03 34

Page 35: Introduction to VB Programming

Arithmetic in VB

• The arithmetic operators used in VB use several special characters:– ^ indicates exponentiation– * indicates multiplication– \ indicates Integer division

• Arithmetic expressions are written in straight-line form.– Ex. a ^ b

04/19/2023 VBN2008-03 35

Page 36: Introduction to VB Programming

Arithmetic in VB

• Most operators are binary, requiring 2 operands.– Ex. sum + value

• However, the unary operator (+, -) requires only one operand.– Ex. -3, +3

04/19/2023 VBN2008-03 36

Page 37: Introduction to VB Programming

Arithmetic Operators

04/19/2023 VBN2008-03 37

VB OperationArithmetic Operator

Algebraic Expression

VB Expression

Addition + x + y x + y

Subtraction - z - 8 z - 8

Multiplication * yb y * b

Division (float) / v/u v / u

Division (Integer) \ none v \ u

Exponentiation ^ q Pq ^ p

Unary Minus & Plus - or + -e or +e -e or +e

Modulus Mod q modulo r q Mod r

Page 38: Introduction to VB Programming

Special Arithmetic Operators

• Integer Division (\) – Supports Byte, Short, Integer, or Long Data

Types– results in an Integer result

• Ex. 8 \ 2 = 4 and 9 \ 5 = 1– Note: Floating point numbers are coerced to

Long (a narrowing conversion) quietly (behind the scene) before Integer Division takes place.• Ex. 7.7 \ 4 = 2 because 8 \ 4 = 2.• the whole part of the floating point result and the rest

is truncated.

04/19/2023 VBN2008-03 38

Weird

!

Page 39: Introduction to VB Programming

Integer Division Examples

Operation Result

Result = 11 \ 4 2

Result = 11.4 \ 4 2

Result = 11.8 \ 4 3

Result = 11 \ 4.2 2

Result = 11 \ 4.8 2

04/19/2023 VBN2008-03 39

Page 40: Introduction to VB Programming

Special Arithmetic Operators

• Modulus (Mod) results in an Integer remainder after Integer Division.

• Ex. X Mod Y = the remainder after X is divided by Y. If the result is 0, then X is evenly divisible by Y.

• Ex. 10 Mod 4 = 2; 10.8 Mod 4 = 3– Note:

• if the Result is defined as a floating point, the result will be the floating point remainder

• Use of the Mod with floating point will introduce a hidden conversion from Single or Double to Integer – possible loss of data

04/19/2023 VBN2008-03 40

Weird

!

Page 41: Introduction to VB Programming

Modulus Examples

Operation Result

Result = 10 Mod 4 2

Result = 10.4 Mod 4 2

Result = 10.8 Mod 4 3

Result = 10 Mod 4.2 2

Result = 10 Mod 4.8 0

*Dim Result As Integer

04/19/2023 VBN2008-03 41

2

4 ) 10

8

2

2

4.8) 10.0

10

0

4.8 rounds to 5

Page 42: Introduction to VB Programming

Modulus Examples

Operation Result

Result = 10 Mod 5 0

Result = 10 Mod 3 1

Result = 12 Mod 4.3 3.4

Result = 12.6 Mod 5 2.6

Result = 47.9 Mod 9.35

1.15

*Dim Result As Double04/19/2023 VBN2008-03 42

2

5 ) 12.6

10

2.6

5

9.35) 47.90

46.75

1.15

Page 43: Introduction to VB Programming

Comparison Operators

04/19/2023 VBN2008-03 43

Standard algebraic equality

operator or relational operator

VB Comparison

OperatorEx. of VB Condition Meaning of VB Condition

= = D = G D is equal to G <> S <> R S is not equal to R> > Y > I Y is greater than I

< < P < M P is less than M >= C >= E C is greater than or equal to E <= M <= S M is less than or equal to S

Page 44: Introduction to VB Programming

Operator Precedence

• Reflects a hierarchical order• Aids evaluation of expressions

– Boolean Relational Operators have the lowest precedence. (to be discussed later)

• Using parentheses ( ) is recommended to:– Avoid syntax errors– Clarify the meaning of the comparison

• Evaluation Trees are used to check logic

04/19/2023 VBN2008-03 44

Page 45: Introduction to VB Programming

Order of Operator Precedence

04/19/2023 VBN2008-03 45

OPERATOR TYPE NAME () Parentheses Parentheses ̂ Arithmetic Exponent

+ - Arithmetic Unary Plus & Unary Minus * / Arithmetic Multiplication, floating-point division

\ Arithmetic Integer division Mod Arithmetic Modulus + - Arithmetic Addition, subtraction

& Concatenation String concatenation= <>

<= >= > <Like Is TypeOf

Comparison (all have same level of precedence)

Equal to, not equal to, less than or equal to, greater than or equal to, greater than, less than; Like, Is, TypeComparison

Not Logical Logical Negation And AndAlso Logical Logical And

Or OrElse Logical Logical OrXor Logical Logical Exclusive Or

See Appendix A

Page 46: Introduction to VB Programming

Line Continuation

• Permits a long line of code to be divided into two lines.– Must be surrounded by at least one

space – Must not have anything after the “_”

• Improves readability• Example:MessageBox.Show(“The Square Root of 2 is “ & root,

_ “The Square Root of 2”)

04/19/2023 VBN2008-03 46

Page 47: Introduction to VB Programming

String Concatenation

• Concatenation Operator is the ampersand “&”

• Is a binary operator• Combines two strings• Example:MessageBox.Show(“The square root of 2 is ” & root)

• Note: If the variable (in this case root) is not a String, VB will automatically create a String representation of the argument.

04/19/2023 VBN2008-03 47

Page 48: Introduction to VB Programming

Common Programming Errors

Syntax Errors

04/19/2023 VBN2008-03 48

Page 49: Introduction to VB Programming

Syntax Errors

• A syntax error, also called a compile error, is a violation of a language’s syntax.

• Occurs when:– statements are missing information– statements have extra information– names are misspelled– punctuation is missing (missing

parentheses)

04/19/2023 VBN2008-03 49

Page 50: Introduction to VB Programming

Syntax Errors - Help

• VB – indicates syntax errors by underlining

the suspect code with a red line– provides an explanation in the Task List

window– Provides a tool tip explaining what

VB.Net thinks is wrong, if you rest the mouse on the error.

04/19/2023 VBN2008-03 50

Page 51: Introduction to VB Programming

Next?

04/19/2023 VBN2008-03 51