Introduction to Visual Basic

Slides:



Advertisements
Similar presentations
Chapter 3 Variables, Constants, and Calculations Copyright © 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved. McGraw-Hill.
Advertisements

Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved. - edited by Maysoon Al-Duwais1.
Objectives Understand the software development lifecycle Perform calculations Use decision structures Perform data validation Use logical operators Use.
Introduction to C Programming
Variables, Constants, and Calculations. Data — Variables and Constants (1 of 2) Variable  Memory locations that hold data that can be changed during.
Chapter 3 Variables, Constants, and Calculations
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Introduction to C Programming
Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic th Edition.
Chapter 3 Variables, Constants, and Calculations Copyright © 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved. McGraw-Hill.
McGraw-Hill © 2009 The McGraw-Hill Companies, Inc. All rights reserved. Chapter 3 Variables, Constants, and Calculations.
McGraw-Hill © 2009 The McGraw-Hill Companies, Inc. All rights reserved. Chapter 3 Variables, Constants, and Calculations.
Chapter 3: Using Variables and Constants
Programming with Microsoft Visual Basic th Edition CHAPTER THREE USING VARIABLES AND CONSTANTS.
© 2006 Lawrenceville Press Slide 1 Chapter 3 Visual Basic Interface.
3-1 aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf.
Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Microsoft Visual Basic 2005 CHAPTER 4 Variables and Arithmetic Operations.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved. 1 5 Completing the Inventory Application Introducing Programming.
Microsoft Visual Basic 2005: Reloaded Second Edition Chapter 3 Variables, Constants, Methods, and Calculations.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved. - edited by Maysoon Al-Duwais1.
Introduction to Visual Basic Programming. Introduction Simple Program: Printing a Line of Text Another Simple Program: Adding Integers Memory Concepts.
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
Chapter 3 Variables, Constants and Calculations Programming In Visual Basic.NET.
Microsoft Visual Basic 2010: Reloaded Fourth Edition Chapter Three Memory Locations and Calculations.
Chapter 4 Variables and constants. 4.1 Variables -Use of variables is good programming style -easier to modify -easier for a programmer to understand.
Variables and Constants Variable Memory locations that hold data that can be changed during project execution Example: a customer’s name Constant Memory.
Programming with Microsoft Visual Basic 2008 Fourth Edition Chapter Three Using Variables and Constants.
Exceptions, handling exceptions & message boxes Year 11 Information Technology.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
3-1 aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf.
Programming with Microsoft Visual Basic th Edition
Chapter 4 Getting Started with VBA. Subroutines Subroutine is the logical section of code that performs a particular task. Subroutine is also called a.
Microsoft Visual Basic 2012 CHAPTER FOUR Variables and Arithmetic Operations.
Microsoft Visual Basic 2012: Reloaded Fifth Edition Chapter One An Introduction to Visual Basic 2012.
Chapter 4.  Variables – named memory location that stores a value.  Variables allows the use of meaningful names which makes the code easier to read.
Slide 1 Chapter 3 Variables  A variable is a name for a value stored in memory.  Variables are used in programs so that values can be represented with.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
© 2006 Lawrenceville Press Slide 1 Chapter 4 Variables  A variable is a name for a value stored in memory.  Variables are created using a declaration.
Slide 1 Chapter 3 Variables  A variable is a name for a value stored in memory.  Variables are created using a declaration statement. For example: Dim.
VISUAL BASIC 6.0 Designed by Mrinal Kanti Nath.
Visual Basic.NET Windows Programming
A variable is a name for a value stored in memory.
Topics Designing a Program Input, Processing, and Output
Chapter 3: Variables, Constants, and Calculations
Chapter 6 JavaScript: Introduction to Scripting
Chapter 1: An Introduction to Visual Basic 2015
Completing the Problem-Solving Process
Chapter 2 - Introduction to C Programming
Chapter 2: Introduction to Visual Basic Programming
Variables and Arithmetic Operations
Chapter 3: Using Variables and Constants
Variables, Expressions, and IO
Introduction to Scripting
Chapter 2 - Introduction to C Programming
Variables and Arithmetic Operations
Chapter 2 - Introduction to C Programming
Introduction to C++ Programming
CIS16 Application Development Programming with Visual Basic
WEB PROGRAMMING JavaScript.
Chapter 2 - Introduction to C Programming
CIS16 Application Development Programming with Visual Basic
Brief description on how to navigate within this presentation (ppt)
Chapter 2 - Introduction to C Programming
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
Chapter 2 - Introduction to C Programming
Brief description on how to navigate within this presentation (ppt)
Presentation transcript:

Introduction to Visual Basic

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.

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. You write code in VB in procedures; currently each procedure will be a sub procedure (Key Term) and begin with the words Private Sub and end with End Sub.

Analyzing the Program Line Numbers Comments 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.

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.

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

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.

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.

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.

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.

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.

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.

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.

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. "

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.

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.

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.

Data — Variables and Constants 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 Dim CustomerNameString As String = “Google" Const SALES_TAX_RATE_Decimal As Decimal = .08D

Data — Variables and Constants 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

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

Constants Named Intrinsic User assigned name, data type, and value Use CONST keyword to declare. Intrinsic System defined within Visual Studio (Color.Red) Const COMPANY_ADDRESS_String As String = "101 S. Main Street" Const SALES_TAX_RATE_Decimal As Decimal = .08D

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.

Declaration Statement Examples Dim CustomerNameString As String Private TotalSoldInteger As Integer Dim TemperatureSingle As Single Dim PriceDecimal As Decimal Private PriceDecimal

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

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

Converting Strings to a Numeric 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. QuantityInteger =Integer.Parse(quantityTextBox.Text) PriceDecimal =Decimal.Parse(priceTextBox.Text) WholeNumberInteger =Integer.Parse(digitString)

Converting to String ResultTextBox.Text =ResultDecimal.ToString( ) Values assigned to string variables or Text properties must be string. Convert any numeric data type to string using .ToString method. ResultTextBox.Text =ResultDecimal.ToString( ) CountTextBox.Text =CountInteger.ToString( ) IDString =IDInteger.ToString( )

Order of Operations Hierarchy of operations, or order of precedence, in arithmetic expressions from highest to lowest 1. Any operation inside parentheses 2. Exponentiation 3. Multiplication and division 4. Integer division 5. Modulus 6. Addition and subtraction

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.

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.Text NameAndAddressLabel.Text=NameTextBox.Text & " " AddressTextBox.Text

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.

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.

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.

Try Block — General Form ‘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

Try Block — Example Catches Any Exception Try QuantityInteger = Integer.Parse(QuantityTextBox.Text) Catch MessageLabel.Text = "Error in input data." End Try

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). MessageBox.Show (TextMessage, TitlebarText, _ MessageBoxButtons, MesssageBoxIcon)

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

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.