49
Introduction to Visual Basic

Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information

Embed Size (px)

Citation preview

Page 1: Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information

Introduction to Visual Basic

Page 2: Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information

Introduction•In this chapter, we introduce Visual Basic programming with program code.

•We demonstrate how to display information on the screen and obtain information from the user at the keyboard.

•You’ll use graphical user interface (GUI) controls to allow users to interact visually with your programs.

•GUIs (pronounced “GOO-ees”) give you app a distinctive look-and-feel.

Page 3: Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information

Introduction Sample GUI

◦ GUIs are built from GUI controls (which are sometimes called components or widgets—short for window gadgets).

◦ GUI controls are objects that can display information on the screen or enable users to interact with an app via the mouse, keyboard or other forms of input (such as voice commands).

Page 4: Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information

Writing the Code•While the project is running, the user can perform actions.

•Each action by the user causes an event to occur.

•Write code for the events you care about; the events you want to respond to with code.

•Code is written as event procedures.

•VB will ignore events for which you do not write code.

•VB will automatically name event procedures as the object name, an underscore(_) and the name of the event.

Page 5: Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information
Page 6: Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information

Analyzing the Program Line Numbers

◦ All of our app listings include line numbers—these are not part of Visual Basic.

◦ The line numbers help us refer to specific parts of an app.

Comments◦ Comments begin with a single-quote character ('), which indicates

that the remainder of the line is a comment.◦ They improve the code’s readability—you can write anything you

want in a comment.◦ Comments can be placed either on their own lines (we call these

“full-line comments”; or at the end of a line of Visual Basic code (we call these “end-of-line comments”).

◦ The compiler ignores comments—they do not cause the computer to perform any actions when an app runs.

Page 7: Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information

Analyzing the Program Classes

◦ Windows Forms apps consist of pieces called classes, which are logical groupings of methods and data that simplify program organization.

◦ Methods perform tasks and can return information when the tasks are completed.

◦ These lines collectively are called a class declaration.◦ Every Windows Forms app consists of at least one class that

typically contains methods that perform tasks.

Page 8: Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information

Analyzing the Program Keywords

◦ The words Public and Class are examples of keywords.◦ Keywords are words reserved for use by Visual Basic.

Page 9: Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information

Analyzing the Program Visual Basic Is Not Case Sensitive

◦ Visual Basic keywords and identifiers are not case sensitive.◦ Uppercase and lowercase letters are considered to be identical, so HelloWorld and helloworld are interpreted as the same identifier.

◦ Although keywords appear to be case sensitive, they’re not.◦ Visual Basic applies its “preferred” case to each letter of a keyword,

so when you type class, for example, the IDE changes the lowercase c to uppercase, as in Class, even though class would be correct.

Page 10: Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information

Analyzing the Program Blank Lines and Whitespace

◦ Blank lines, space characters and tab characters are used throughout a program to make it easier to read.

◦ These are called whitespace.◦ Blank lines are ignored by the compiler.

Page 11: Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information

Analyzing the Program The Form’s Method BooksButton_Click Event ◦ GUIs are event driven.◦ When the user interacts with a GUI component, the interaction—

known as an event—causes the program to perform a task by “calling” a method.

◦ Common events (user interactions) include clicking a Button, selecting an item from a menu, closing a window and moving the mouse.

Page 12: Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information

Analyzing the Program•All GUI controls, including Forms, have events associated with them.

•A method that performs a task in response to an event is called an event handler, and the process of responding to events is known as event handling.

•Most of a GUI app’s functionality executes based on events.

•Event handling methods are called automatically.

Page 13: Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information

Analyzing the Program Defining a Method

◦ The keyword Sub begins the method declaration (the code that will be executed by this method).

◦ The keywords End Sub close the method declaration.◦ The body of the method declaration appears between the lines of code

containing the keywords Sub and End Sub.◦ The keyword Sub is short for “subroutine”—an early term for

method.◦ Methods are also sometimes called procedures.

Page 14: Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information

Analyzing the Program Indentation

◦ Indentation improves program readability.◦ The indentation is whitespace and is ignored by the

compiler.◦ In Visual Basic, the IDE indents the statements in a

method’s body for you.

Page 15: Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information

Analyzing the Program The expression PromotionLabel.Text contains two identifiers (that is, PromotionLabel and Text) separated by the dot separator (.).

The identifier to the right of the dot separator is the property name, and the identifier to the left of the dot separator is the name of the Label control.

When you add a Label to a Form, the IDE gives it the name PromotionLabel by default for the first Label you add.

After the statements execute, the program reaches the keywords End Sub, which indicate that this method has completed performing its task.

The keywords End Class, indicate the end of the Class.

Page 16: Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information

Analyzing the Program

Syntax Shading◦ The code coloring scheme used by the IDE—called syntax-color

highlighting—helps you visually differentiate program elements.◦ Keywords appear in dark blue.◦ Comments are colored green.◦ Other program elements use different colors.

Page 17: Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information

Continuing Long Program Lines•For long lines of code, it is more readable to continue them on the next line.

•At the end of the line use a Line Continuation Character (a Space, an Underscore and press Enter).

GreetingsLabel.Text="Greetings " & NameTextBox.Text & ":" & _"You have been selected to win a free prize. " & _

"Just send us &100 for postage and handling. "

Page 18: Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information
Page 19: Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information

Intellisense Writing Code and Using IntelliSense

◦ This IDE feature, called IntelliSense, lists keywords, class names, members of a class (which include property and method names) and other features that start with the same characters you’ve typed so far.

◦ Tabs (Common and All) are provided in the IntelliSense window so that you can view either the most commonly used matches or all available matches.

◦ As you type characters, IntelliSense highlights the first item that matches the characters typed so far, then displays a tool tip containing information about that item.

Page 20: Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information

Finding and Fixing Errors•Syntax Errors

• Breaks VB’s rules for punctuation, format, or spelling

• Smart editor finds most syntax errors, compiler finds the rest.

• The editor identifies a syntax error with a squiggly blue line and you can point to an error to pop up the error message.

• You can display the Error List window and line numbers in the source code to help locate the error lines.

•Run-Time Errors• Statements that fail to execute, such as impossible arithmetic operations

•Logic Errors• Project runs, but produces incorrect results.

Page 21: Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information
Page 22: Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information

Addition Program•We’ll now build an Addition app that allows the user to enter two integers (whole numbers) then click an Add Button to calculate their sum and display the result.

•First, we’ll discuss the GUI and the app's code.

•Then, we’ll show how to lay out the GUI and create the addButton_Click event handler that’s called when the user clicks the button.

•The sample output that follows the code shows the GUI after the user has entered two integers and clicked the Add button to display the result.

Page 23: Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information

Addition Program•We’ll now build an Addition app that allows the user to enter two integers (whole numbers) then click an Add Button to calculate their sum and display the result.

•First, we’ll discuss the GUI and the app's code.

•Then, we’ll show how to lay out the GUI and create the addButton_Click event handler that’s called when the user clicks the button.

Page 24: Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information

Data — Variables and Constants (1 of 2)Variable

◦ Memory locations that hold data that can be changed during project execution

◦ Example: customer’s name

Named Constant

◦ Memory locations that hold data that cannot be changed during project execution

◦ Example: sales tax rate

24

Dim CustomerNameString As String = “Google"

Const SALES_TAX_RATE_Decimal As Decimal = .08D

Page 25: Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information

Data — Variables and Constants (2 of 2)

In Visual Basic, when you declare a Variable or Named Constant ◦ An area of memory is reserved◦ A name is assigned called an Identifier◦ Follow rules and naming conventions

Use Declaration Statements to establish Variables and Constants,◦ Assign name and data type,◦ Not executable unless initialized on same line

25

Page 26: Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information

Naming Variables and Constants

Must follow Visual Basic Naming Rules

Should follow Naming Conventions◦ Meaningful names consisting of letters, digits, and underscores;

must begin with a letter and no spaces or periods. Include class (data type) of variable (variable: countInteger constant: QUOTA_Integer)

◦ Use mixed case for variables and uppercase for constants (QuantityInteger).

◦ Cannot use reserved words or keywords to which Basic has assigned a meaning, such as print, name, and value

26

Page 27: Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information

Constants Named

◦ User assigned name, data type, and value◦ Use CONST keyword to declare.

Intrinsic◦ System defined within Visual Studio (Color.Red)

27

Const COMPANY_ADDRESS_String As String = "101 S. Main Street"Const SALES_TAX_RATE_Decimal As Decimal = .08D

Page 28: Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information

Declaring Variables•Declared inside a procedure using a Dim statement

•Declared outside a procedure using Public, Private, or Dim statements

•Always declare the variable’s data type.

•May declare several variables with one statement (unless assigning initial value).

•Use IntelliSense to assist in writing statements.

28

Page 29: Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information

Declaration Statement ExamplesDim CustomerNameString As String

Private TotalSoldInteger As Integer

Dim TemperatureSingle As Single

Dim PriceDecimal As Decimal

Private PriceDecimal As Decimal

3-29

Page 30: Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information
Page 31: Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information

Option Explicit and Option Strict•Option Explicit forces variables to be declared before using.

•Option Strict•Makes VB a strongly typed language like C++, Java and C#•Does not allow implicit conversions from a wider data type to

a narrower one or between String and numeric data types•Best practice to always turn both on either in code or in

Project Properties dialog box

31

Page 32: Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information

Calculations•Calculations can be performed with variables, constants, properties of certain objects, and numeric literals.

•Do not use strings in calculations.

•Values from Text property of Text Boxes•Are strings, even if they contain numeric data•Must be converted to a numeric data type before performing

a calculation

32

Page 33: Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information

Converting Strings to aNumeric Data Type•Use Parse methods to convert the Text property to its numeric form before it’s used in a calculation.

•Each numeric data type class has a Parse method.

•Parse method returns a value that can be used in calculations.

•Parse method fails if user enters nonnumeric data or leaves data blank.

33

QuantityInteger =Integer.Parse(quantityTextBox.Text)PriceDecimal =Decimal.Parse(priceTextBox.Text)WholeNumberInteger =Integer.Parse(digitString)

Page 34: Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information

Converting to String•Values assigned to string variables or Text properties must be string.

•Convert any numeric data type to string using .ToString method.

34

ResultTextBox.Text =ResultDecimal.ToString( )CountTextBox.Text =CountInteger.ToString( )IDString =IDInteger.ToString( )

Page 35: Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information

Conversion Methods

3-35

Method Convert ToInteger.Parse IntegerDecimal.Parse Decimal.ToString String

Page 36: Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information
Page 37: Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information

Order of Operations Hierarchy of operations, or order of precedence, in arithmetic expressions from highest to lowest

1. Any operation inside parentheses2. Exponentiation3. Multiplication and division4. Integer division5. Modulus6. Addition and subtraction

37

Page 38: Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information
Page 39: Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information

Compound Assignment Operators The compound assignment operators enable you to abbreviate assignment statements.

For example, the statement◦ value = value + 3

which mentions the variable value on both sides of the assignment, can be abbreviated with the addition assignment operator, += as

◦ value += 3

The += operator adds the value of the right operand to the value of the left operand and stores the result in the left operand’s variable.

Page 40: Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information
Page 41: Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information

Concatenation•Think of concatenation as "tacking" text strings together.

•Use an ampersand (&) preceded and followed by a space between the two strings.

Example:

MessageLabel.Text="Your name is: " & NameTextBox.TextNameAndAddressLabel.Text=NameTextBox.Text & " " AddressTextBox.Text

Page 42: Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information

Addition Program What if the User Doesn’t Enter an Integer?

◦ For this program, if the user types a noninteger value, such as "hello," a runtime error (an error that has its effect at execution time) occurs.

◦ Need to prevent the error from crashing the program.◦ We will “catch”, or “handle” the error, called an exception, when it happens

to prevent the program from crashing.

Page 43: Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information

Handling Exceptions•Use structured exception handling to easily catch errors before run-time error occurs.

•Catching exceptions is referred to as error trapping.

•Coding to handle exception is called error handling.

•Each exception is an instance of the Exception class. The properties of this class allow you to determine the code location of the error, the type of error, and cause.

43

Page 44: Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information

Try/Catch Blocks•Enclose statements that might cause an error within Try/Catch block.

• If an exception occurs while statements in the Try block are executing, program control is transferred to the Catch Block.

• If a Finally statement is included, the code in that section executes last, whether or not an exception occurred.

44

Page 45: Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information

Try Block — General Form

45

Try‘statements that may cause an error

Catch [VariableName As ExceptionType]‘statements for action when an exception occurs

[Finally‘statements that always execute before exit of the Try

block]End Try

Page 46: Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information

Try Block — ExampleCatches Any Exception

46

Try

QuantityInteger = Integer.Parse(QuantityTextBox.Text)

Catch

MessageLabel.Text = "Error in input data."

End Try

Page 47: Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information

MessageBox Object (1 of 2)•The MessageBox is an overloaded method.

• Signatures correspond to the argument list.• There are multiple signatures to choose from.• Do not reverse, transpose, or leave out any of the arguments.• IntelliSense displays argument list (also called signatures).

47

MessageBox.Show (TextMessage, TitlebarText, _ MessageBoxButtons, MesssageBoxIcon)

Page 48: Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information

MessageBox Object (2 of 2)•TextMessage string

• String literal or variable that displays message

•Title Bar text• String that appears in title bar of message box

•MessageBox Buttons• OK, OKCancel, RetryCancel, YesNo, YesNoCancel, AbortRetryIgnore

•MessageBox Icons• Asterisk, Error, Exclamation, Hand, Information, None, Question,

Stop, Warning

48

Page 49: Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information

Using Overloaded Methods•This OOP feature allows the Show method to act differently for different arguments.

•Each argument list is called a signature so the Show method has several signatures.

•Supplied arguments must exactly match one of the signatures provided by the method.

•IntelliSense in Visual Studio editor helps when entering arguments so that they don’t need to be memorized.

49