1 / 43

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 on the screen and obtain information from the user at the keyboard.

okg
Download Presentation

Introduction to Visual Basic

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Introduction to Visual Basic

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  21. Constants • Named • 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

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

  23. Declaration Statement Examples

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

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

  26. 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. QuantityInteger =Integer.Parse(quantityTextBox.Text) PriceDecimal =Decimal.Parse(priceTextBox.Text) WholeNumberInteger =Integer.Parse(digitString)

  27. Converting to String • 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( )

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

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

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

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

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

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

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

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

  36. 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)

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

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

More Related