Programming Practice in Visual Basic The Initial Visual Basic Screen Toolbox Project Explorer window Properties window Form Menu bar Description pane.

Slides:



Advertisements
Similar presentations
Working with Intrinsic Controls and ActiveX Controls
Advertisements

Objectives Understand the software development lifecycle Perform calculations Use decision structures Perform data validation Use logical operators Use.
VB Numbers and Strings School of Business Eastern Illinois University (Week 4, Monday 2/03/2003) © Abdou Illia, Spring 2003.
Chapter 2 –Visual Basic, Controls, and Events
Introduction to Visual Basic Programming. Lecture Outline History What is Visual Basic First Look at the VB 6.0 Environment Some VB Terminology Our first.
Fundamentals of Programming in Visual Basic
Input Dialog Box An input dialog box can be used to obtain a single item of input from the user Presents a window (dialog box) requesting input Syntax:
Fundamentals of Programming in Visual Basic
1 Outline 13.1Introduction 13.2A Simple Program: Printing a Line of Text in a Web Page 13.3Another JavaScript Program: Adding Integers 13.4Memory Concepts.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
The Initial Visual Basic Screen
VB Code Statements 3 types of VB statement The Remark statement, known as comments, are used for project documentation only Begin with an apostrophe Not.
Fundamentals of Programming in Visual Basic
Chapter 2 –Visual Basic, Controls, and Events
Variables & Math Operators CE 311 K - Introduction to Computer Methods Daene C. McKinney.
Chapter 31 Fundamentals of Programming in Visual Basic (Continue VI) String Properties and Methods: "Visual".Length is 6. "Visual".ToUpper is VISUAL. "123.
1 Chapter 3 – Variables, Input, and Output 3.1 Numbers 3.2 Strings 3.3 Input and Output.
Fundamentals of Programming in Visual Basic
Visual Basic Chapter 1 Mr. Wangler.
Variables and Constants
05/09/ Introducing Visual Basic Sequence Programming.
© 2006 Lawrenceville Press Slide 1 Chapter 3 Visual Basic Interface.
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 7 - JavaScript: Introduction to Scripting Outline 7.1 Introduction 7.2 Simple Program: Printing.
Chapter 3 - VB.NET by Schneider1 Chapter 3 – Fundamentals of Programming in VB.NET VB.NET Controls VB.NET Events Numbers Strings Input and Output.
CS0004: Introduction to Programming Variables – Strings.
1 Chapter 3 – Variables, Input, and Output 3.1 Numbers 3.2 Strings 3.3 Input and Output.
1 Chapter 3 – Variables, Input, and Output 3.1 Numbers 3.2 Strings 3.3 Input and Output.
Chapter 3 - VB 2008 by Schneider1 Chapter 3 – Variables, Input, and Output 3.1 Numbers 3.2 Strings 3.3 Input and Output.
Introduction to Visual Basic.NET Chapter 2 Introduction to Controls, Events.
Input, Output, and Processing
Copyright © 2001 by Wiley. All rights reserved. Chapter 2: Using Visual Basic to Create a First Project Getting Started with VB Development Environment.
 Application – another name for a program.  Interface – is what appears on the screen when the application is running.  Program Code – is instructions.
Chapter One An Introduction to Visual Basic 2010 Programming with Microsoft Visual Basic th Edition.
Copyright © 2012 Pearson Education, Inc. Chapter 2: Introduction to C++
Introduction to Programming with RAPTOR
Chapter Two Creating a First Project in Visual Basic.
Microsoft Visual Basic 2005: Reloaded Second Edition Chapter 3 Variables, Constants, Methods, and Calculations.
Numbers continued The Integer Data Type Multiple Declarations Parentheses Three Types of Errors.
Chapter 8 - Visual Basic Schneider
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Variables & Function Calls. Overview u Variables  Programmer Defined & Intrinsic  Data Types  Calculation issues u Using Functions  The val() function.
 2000 Deitel & Associates, Inc. All rights reserved. Outline 8.1Introduction 8.2A Simple Program: Printing a Line of Text in a Web Page 8.3Another JavaScript.
Introduction to Programming Fundamentals of Programming in Visual Basic.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Hungarian Notation A must in this course Every object used MUST be renamed including the form(s) using the following rules Form  frmFormName E.g. frmTemperature.
Chapter 3 - Visual Basic Schneider Numeric Variables Used to store numbers Value is assigned by a statement of the form: numVar = expression The variable.
Tutorial 3: Using Variables and Constants1 Tutorial 3 Using Variables and Constants.
Part:2.  Keywords are words with special meaning in JavaScript  Keyword var ◦ Used to declare the names of variables ◦ A variable is a location in the.
Chapter 4 Getting Started with VBA. Subroutines Subroutine is the logical section of code that performs a particular task. Subroutine is also called a.
Variables and Expressions Programming Right from the Start with Visual Basic.NET 1/e 7.
Microsoft Visual Basic 2012 CHAPTER FOUR Variables and Arithmetic Operations.
Visual Basic.NET Programming for the Rest of Us Keith Mulbery Utah Valley State College.
Microsoft Visual Basic 2012: Reloaded Fifth Edition Chapter One An Introduction to Visual Basic 2012.
Chapter 2 - VB 2008 by Schneider1 Chapter 2 –Visual Basic, Controls, and Events 2.1 An Introduction to Visual Basic 2.2 Visual Basic Controls 2.3 Visual.
Chapter 4.  Variables – named memory location that stores a value.  Variables allows the use of meaningful names which makes the code easier to read.
Chapter 3 - VB 2008 by Schneider1 Chapter 3 – Variables, Input, and Output 3.1 Numbers 3.2 Strings 3.3 Input and Output.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
Chapter 3 - Visual Basic Schneider. Private Sub cmdEvaluate_Click() Dim n As Single, root As Single n = 6.76 root = Sqr(n) picResults.Print root; Int(n);
Chapter 6 JavaScript: Introduction to Scripting
Variables, Expressions, and IO
Variables and Arithmetic Operations
Fundamentals of Programming in Visual Basic
Introduction to C++ Programming
WEB PROGRAMMING JavaScript.
Fundamentals of Programming in Visual Basic
Building an Application in the Visual Basic .NET Environment
Additional Topics in VB.NET
Chapter 2: Introduction to C++.
Introduction to Programming
Presentation transcript:

Programming Practice in Visual Basic

The Initial Visual Basic Screen Toolbox Project Explorer window Properties window Form Menu bar Description pane Form Layout window Toolbar Project Container window

Steps to Create a Visual Basic Program 1. Create the interface by placing controls on the form 2. Set properties for the controls and the form 3. Write code for event procedures associated with the controls and the form

Four Useful Visual Basic Controls Text Boxes Labels Command Buttons Picture Boxes

Placing a Text Box on a Form Double-click on the text box icon in the toolbox to add a text box to your form Activate the properties window (Press F4) Set values of properties for text box

Placing a Text Box on a Form Text box

Some Useful Properties of Objects Name Caption Text (for Text Boxes) BorderStyle Visible BackColor Alignment Font Border Style: Setting the BorderStyle to 0-None removes the border from an object Visible: Setting the property to false hides an object when the program run. The object can be set to reappear with code BackColor: Specifies the background color for text box, label, picture box or form.. Also specific background color for a command button having Style set to “1-Graphical” BackStyle: The background of a label is opaque by default. Setting the background style of a label to transparent causes whatever is behind the label remain visible.; the background color of the label essentially becomes “see through” Font: Two unusual fonts are Symbols and Wingdings> For instance with the windingsfonts, changing the text to % & ‘ and J yields a bell, a book, a candle and a smiling face

Example

Naming Objects: Use the Property window to change the Name property of an object Good programming practice dictates that each object name begins with a three letter prefix that identifies the type of object.

Naming Objects:

Naming Objects An Object Name Must Start with a letter Can include numbers and underscore (_) Cannot include punctuation or spaces Can be a maximum of 40 characters

Visual Basic Events Code is a set of statements that instruct the computer to carry out a task. Code can be associated with events When an event occurs, the code associated with that event (called an Event Procedure) is executed.

Creating An Event Procedure Double-click on an object to open a Code window. (The empty default event procedure will appear. Click on the Procedure box if you want to display a different event procedure.) Write the code for that event procedure.

Example of An Event Procedure Private Sub objectName_event ( ) ‘Here are your statements’ End Sub Private Sub txtOne_GotFocus( ) txtOne.Font.Size = 12 txtOne.Font.Bold = False End Sub

More Examples Private Sub cmdButton_Click( ) txtBox.ForeColor = vbRed txtBox.Font.Size = 24 txtBox.Text = “Hello” End Sub

Exercises 11. Private Sub cmdButton_Click( ) txtOne.text = “Hello Doctor” End Sub 12. Private Sub cmdButton_Click( ) txtOne.ForeColor = “red” End Sub

Exercises 13. Private Sub cmdButton_Click( ) txtBox.Caption = “Hello” End Sub 16. Private Sub cmdButton_Click( ) txtOne.MultiLine= True End Sub

Tips Most Properties can be set or altered at run time with code. cmdButton.visible = False The BorderStyle and MultiLine properties of a text box can only be set from the properties window “” surrounds Caption, Name, Font.Name or strings not True, vars or numeric constants

Color Constants At design time colors are selected from a palette At run time the eight most common colors can be assigned with the color constants: vbBlackvbMagenta vbRedvbCyan vbGreenvbYellow vbBluevbWhite

Components of Visual Basic Statements Constants Variables Keywords (reserved words)

Constant Can NOT change during the execution of a program. Types of Constants: numeric constants string constants

Valid Numeric Constants: Integer Real number

Invalid Numeric Constants: 14, % 33- $ &

String Constants: A sequence of characters treated as a single item The characters in a string must be surrounded by double quotes (“ ”)

Valid String Constants “A rose by any other name” “9W” “134.23” “She said, ‘stop, thief!’ ”

Invalid String Constants ‘Down by the Seashore’ “ “She said, “Stop, thief!””

Arithmetic Operations Operator Operation Basic expression ^ Exponentiation A ^ B * Multiplication A * B / Division A / B + Addition A + B - Subtraction A - B

Variables A storage location in main memory whose value can be changed during program execution. These storage locations can be referred to by their names. Every variable has three properties: a Name, a Value, and a Data Type. Types of variables: Numeric and String

Rules for Naming Variables Must begin with a letter Must contain only letters, numeric digits, and underscores ( _ ) Can have up to 255 characters Cannot be a Visual Basic language keyword (for example, Sub, End, False) VB does not distinguish between uppercase and lowercase letters. Example: numberOfCars, tax_Rate_1994 Let statement assigns values to variables and Print method displays the values of variable.

Numeric Variables Used to store numbers Value is assigned by a statement of the form: numVar = expression The variable must be on the left and the expression on the right.

Valid Numeric Variable Names: Chapter 3 - Visual Basic Schneider timeElapsed taxRate speed n celsius

Invalid Numeric Variable Names: Chapter 3 - Visual Basic Schneider maximum/average 1stChoice square yard

String Variables A string variable stores a string. The rules for naming string variables are identical to those for naming numeric variables. When a string variable is first declared, its value is the empty string.

String Variable Example Private Sub cmdShow_Click() picOutput.Cls phrase = "win or lose that counts." picOutput.Print "It's not whether you "; phrase picOutput.Print "It's whether I "; phrase End Sub

Concatenation Two strings can be combined by using the concatenation operation. The concatenation operator is the ampersand (&) sign.

Examples of Concatenation: strVar1 = “Hello” strVar2 = “World” picOutput.Print strVar1& strVar2 txtBox.Text = “32” & Chr(176) & “ Fahrenheit”

Assignment Statement: The statement var = expr assigns the value of the expression to the variable tax = 0.02 * (income * dependents) sum = 2 + x y

Valid Assignment Statements count = count + 1 num = 5 count = count + num /2

Invalid Assignment Statements 10 = count count + 1 = count

Keywords Words that have predefined meaning to Visual Basic. Can Not be used as variable names. Examples: End- Print Sub- Let If -Select While-Call The VB editor automatically capitalizes the first letter of reserved word

Visual Basic Print Statement Print is a method used to display data on the screen or printer. Can be used to display values of variables or expressions Private Sub cmdCompute_Click() picResults.Print picResults.Print picResults.Print 3 * 2 picResults.Print 3 / 2 picResults.Print 3 ^ 2 picResults.Print 2 * (3 + 4) End Sub

Examples of Print Statements x = 15 y = 5 picOutput.Print (x + y) / 2, x / y Output: 103

Declaring Variable Types Use the Dim statement to declare the type of a variable. Examples: Dim number As Integer Dim flower As String Dim interestRate As Single From now on we will declare all variables. Declaring variables is regarded as good programming practice.

Data Types : Single: a numeric variable that stores real numbers Integer: a numeric variable that stores integer numbers (from to 32767) String: a variable that stores a sequence of characters

Using Text Boxes for Input/Output The contents of a text box are always a string. Numbers can be stored in text boxes as strings.

Using Text Boxes for Input/Output The contents of a text box should be converted to a number before being assigned to a numeric variable. Val(txtBox.Text) gives the value of a numeric string as a number Example: Dim numVar as Single numVar = Val(txtBox.Text)

Example (convert miles to furlongs and vice versa) Example 1 xString=“528” xValue=Val(xString)  xValue=528 Example 2 yValue=428 yString=Str(yValue)  yString=“428”

Example (convert miles to furlongs and vice versa) Private Sub txtFurlong_LostFocus() txtMile.Text = Str(Val(txtFurlong.Text / 8)) End Sub Private Sub txtMile_LostFocus() txtFurlong.Text = Str(8 * Val(txtMile.Text)) End Sub

Program Documentation An apostrophe ( ' ) is used to indicate that the remainder of the line is a comment. (Comments are ignored by Visual Basic.) Remarks can appear on a separate line or following a Visual Basic statement.

Using Message Dialog Box for Output The message dialog box is used to present a pop-up window containing information for the user Syntax: MsgBox prompt,, title

Example of a Message Dialog Box MsgBox “Nice try, but no cigar”,, “Consolation” Stays on the screen until the user presses OK

Formatting the Output: Create easily readable output In the Print method, the spacing of the output is controlled by the following devices: semicolon comma Tab function

Semicolons The next value output is placed in the next column position. Example: picOutput.Print “Patrick”; ”Jon” Output: PatrickJon

Example of Semicolon Chapter 3 - Visual Basic Schneider picOutput.Print 100; -200; 300 Output Screen: One space Two spaces

Commas Chapter 3 - Visual Basic Schneider A comma in a Print method causes the next value output to be placed in the next available print zone. Each print zone is 14 positions wide.

Using Commas Example: picOutput.Print “SEE”, ”YOU”, ”SOON” Output Screen: SEE YOU SOON Column 1 Column 15 Column 29

Using Commas Example: picOutput.Print “abc123def456ghi”, ”whatever” Output Screen: abc123def456ghi whatever Column 1 Column 15 Column 29

Using Commas A print zone can be skipped by typing consecutive commas Example: picOutput.Print “HOURLY”,, “PAY” Output Screen: HOURLY PAY Column 29

Tab Function Specifies the column where output will start Use only semicolons with the Tab function Can only be used to advance the print position (cannot move backwards)

Example of Tab Function Example: picOutput.Print Tab(3); “Hi there!” ; Tab(25) ;“Bye!” Output Screen: Hi there! Bye! Column 3 Column 25

Built-In Functions Take one or more input values and return an output value A means provided by Visual Basic for carrying out small, common tasks Types of Built-In functions Numeric functions (manipulate numbers) String functions (manipulate strings)

Numeric Functions

Example of Numeric Functions Private Sub cmdEvaluate_Click() Dim n As Single, root As Single n = 6.76 root = Sqr(n) picResults.Print root; Int(n); Round(n,1) End Sub Output:

Commonly-Used String Functions Function: Left(“Penguin”, 4) Purpose: Returns the number of characters specified, starting at the beginning of the string

Commonly-Used String Functions Function: Right(“Gotham City”, 4) Purpose: Returns the number of characters specified from the end of the string

Commonly-Used String Functions Function: Mid(“Commissioner”, 4, 3) Purpose: Returns the substring starting at the position indicated by the first number and continuing for the length specified by the second number

Commonly-Used String Functions Function: UCase(“Yes”) Purpose: Converts any lowercase letters in a string to uppercase

String-Related Numeric Functions Function: InStr(“John Smith”, “m”) Purpose: Searches for the first occurrence of one string in another and gives the position at which the string is found

String-Related Numeric Function Function: Len(“John Smith”) Purpose: Returns the number of characters in the string.

Strings and string Functions examples picBoard.print len(left(“welcome”,3)) picBoard.print UCase(left(“welcome”,3))

Format Functions The format functions provide detailed control of how numbers, dates, and strings are displayed. Examples FormatNumber ( , 1) 12,345.7 FormatCurrency ( , 2) $12, FormatPercent (.185, 2) 18.50% FormatNumber (1 + Sqr(2), 3) 2.414

Format Function Format (expr, Purpose: The value of this function is the value of expr right justified in a field of n spaces, where n is the number symbols.

Format Examples Format(12345, Format(123, 123 Format(“123.4”, 123.4

Rnd Function Chapter 3 - Visual Basic Schneider Returns a random number from 0 to 1. (excluding 1). Example: picBox.Print Rnd Output: Displays a random number from 0 to 1 (0 included and 1 excluded). Example: picBox.Print Rnd +5 Output: Displays a random number from 5 to 6 (5 included and 6 excluded).