Presentation is loading. Please wait.

Presentation is loading. Please wait.

Starting Out with Visual Basic.NET 2 nd Edition Chapter 3 Input, Variables, Constants, And Calculations.

Similar presentations


Presentation on theme: "Starting Out with Visual Basic.NET 2 nd Edition Chapter 3 Input, Variables, Constants, And Calculations."— Presentation transcript:

1 Starting Out with Visual Basic.NET 2 nd Edition Chapter 3 Input, Variables, Constants, And Calculations

2 Starting Out with Visual Basic.NET 2 nd Edition 3.1 Introduction

3 Starting Out with Visual Basic.NET 2 nd Edition Chapter 3 Topics This chapter covers the use of text boxes to gather input from users It also discusses the use of variables named constants intrinsic functions mathematical calculations

4 Starting Out with Visual Basic.NET 2 nd Edition 3.2 Gathering Text Input In This Section, We Use the Textbox Control to Gather Input That the User Has Typed on the Keyboard

5 Starting Out with Visual Basic.NET 2 nd Edition Placing Text into a Label, I We have done this already: lblSet.Text = "Place this text in a TextBox" The lblSet.Text is in the form: Object.Property

6 Starting Out with Visual Basic.NET 2 nd Edition Placing Text into a Label, II The text can come from a textBox where the user has typed in input: lblSet.Text = txtInput.Text Notice two use of the form: Object.Property

7 Starting Out with Visual Basic.NET 2 nd Edition Clearing a Text Box, I This can be done with an assignment: txtInput.Text = "" Two adjacent quote marks yields a null string So this statement replaces whatever text that may have been in txtInput with "nothing" -- a string with no characters in it

8 Starting Out with Visual Basic.NET 2 nd Edition Clearing a Text Box, II This can be done with a method: txtInput.Clear() Clear is called a Method Methods do actions -- here clearing the text The syntax is similar to that of referring to a Property: Object.Method

9 Starting Out with Visual Basic.NET 2 nd Edition String Concatenation, I In our code we will often need to combine two or more strings into a longer one This operation is called "Concatenation" Concatenation is signaled with the operator '&' much in the same way that addition is signaled by the operator '+'

10 Starting Out with Visual Basic.NET 2 nd Edition String Concatenation, II Say our user has entered their name into txtUserName, a TextBox In label lblGreeting we want to say, Hello Simply: lblGreeting.Text = "Hello " & txtUserName.Text Put "Hello" on the front of the user's name and place the result into lblGreeting

11 Starting Out with Visual Basic.NET 2 nd Edition The Focus Method, I For a control to have the focus means that it is ready to receive the user's input In a running form, one of the controls always has the focus The control with the focus may be set by program control using the Focus Method: txtUserName.Focus()

12 Starting Out with Visual Basic.NET 2 nd Edition The Focus Method, II You can tell which control has focus by its characteristics: When a TextBox has focus, it will have a blinking cursor or the text inside of the box is highlighted When a button, radio button, or a check box has focus, it will have a thin dotted line around the control

13 Starting Out with Visual Basic.NET 2 nd Edition Controlling a Form’s Tab Order with the TabIndex Property Stepping the focus from one control to another can be done using the Tab Key This order is set for a control relative to others by the value of the TabIndex Property With each Tab Key hit, the focus will step to the control with the next highest value of the TabIndex Property

14 Starting Out with Visual Basic.NET 2 nd Edition Assigning Keyboard Access Keys to Buttons Imagine your form has a button with the text "Save" on it And you wish to allow the user to be able to hit Alt-S to activate that button Simply change the button text to "&Save" The '&' tells Visual Basic.NET to use Alt-S as an access key

15 Starting Out with Visual Basic.NET 2 nd Edition '&' is a Special Character in Button Labels Note that the '&' in "&Save" does not display on the button It simply establishes the Alt Key access In order to actually display an '&' on a button, one must enter it as "&&" (then one will appear and will not cause an Alt Key access to be established)

16 Starting Out with Visual Basic.NET 2 nd Edition Using Access Keys with Labels, I Want to establish an access key for a TextBox? The previous technique will not work because the text of a TextBox is normally a changing value However, there is a way to accomplish the same effect

17 Starting Out with Visual Basic.NET 2 nd Edition Using Access Keys with Labels, II For a Label that immediately precedes a TextBox Assign that Label an access key (labels do not normally have access keys) Set the UseMnemonic Property to True When the user activates the Label's access key, the following TextBox will receive the focus

18 Starting Out with Visual Basic.NET 2 nd Edition Setting the Accept Button The Accept Button is the one that implicitly will be activated if the user hits the Enter Key The AcceptButton Property designates which button on the form is to behave in this manner

19 Starting Out with Visual Basic.NET 2 nd Edition Setting the Cancel Button The Cancel Button is the one that implicitly will be activated if the user hits the Escape Key The CancelButton Property designates which button on the form is to behave in this manner

20 Starting Out with Visual Basic.NET 2 nd Edition 3.3 Variables An Application Uses Variables to Hold Information So It May Be Manipulated, Used to Manipulate Other Information, or Remembered for Later Use

21 Starting Out with Visual Basic.NET 2 nd Edition Why Have Variables? A variable is a storage location in the computer’s memory, used for holding information while the program is running The information that is stored in a variable may change, hence the name “variable”

22 Starting Out with Visual Basic.NET 2 nd Edition What Can You Do With Variables? Copy and store values entered by the user, so they may be manipulated Perform arithmetic on values Test values to determine that they meet some criterion Temporarily hold and manipulate the value of a control property Remember information for later use in the program

23 Starting Out with Visual Basic.NET 2 nd Edition How to Think About Variables You the programmer make up a name for the variable Visual Basic.NET associates that name with a location in the computer's RAM The value currently associated with the variable is stored in that memory location

24 Starting Out with Visual Basic.NET 2 nd Edition Setting the Value of a Variable An assignment statement is used to set the (new) value of a variable, as in: length = 112 greeting = "Good Morning " & txtName.Text

25 Starting Out with Visual Basic.NET 2 nd Edition Variable Declarations A variable declaration is a statement that causes Visual Basic.NET to create a variable in memory As in Dim length As Integer

26 Starting Out with Visual Basic.NET 2 nd Edition Declaration Syntax The official syntax is Dim VariableName As DataType where Dim (stands for Dimension) is a keyword VariableName is the name to be used As is a keyword DataType is the type of the variable and will be one of many possible keywords

27 Starting Out with Visual Basic.NET 2 nd Edition Visual Basic.NET Data Types Boolean Byte Char Date Decimal Double Integer Long Object Short Single String

28 Starting Out with Visual Basic.NET 2 nd Edition Variable Naming Rules The first character of a variable name must be a character or an underscore Subsequent characters may be either of those plus the numeric digits Thus variable names cannot contain spaces or periods (or many other kinds of characters) Variable names must not be keywords

29 Starting Out with Visual Basic.NET 2 nd Edition Variable Naming Conventions Each variable name should describe its use, e.g., itemsOrdered When multiple words are used in a name, capitalize the initials, except for the first one (again, itemsOrdered) As noted earlier, control names should have a specific prefix, e.g. btn for Button controls

30 Starting Out with Visual Basic.NET 2 nd Edition Auto List Feature As you are entering your Visual Basic.NET program, VB will often aid you by offering a list of choices for that could be entered next Right after you type "As" in a variable declaration, Visual Basic.NET will offer you a list of all of the established data types Either choose one or keep typing

31 Starting Out with Visual Basic.NET 2 nd Edition Variable Default Values When a variable is first created in memory, Visual Basic.NET assigns it a default value numeric types are given a value of zero strings are given a value of Nothing dates default to 12:00:00 AM January 1,1

32 Starting Out with Visual Basic.NET 2 nd Edition Initialization of Variables via the Declaration It is preferable to establish your program's own initial value for variables that will not otherwise be given values before they are used In the declaration, simply append " = value" Dim length As Integer = 112

33 Starting Out with Visual Basic.NET 2 nd Edition Scope of a Variable, I A variable’s scope is the part of the program where the variable is visible and may be accessed by programming statements

34 Starting Out with Visual Basic.NET 2 nd Edition Scope of a Variable, II The scope of a variable begins where it is declared And extends to the end of the procedure in which it appears This kind of variable is called local A local variable is declared inside a procedure The variable is not visible outside of the procedure and its name cannot be declared again within the same procedure

35 Starting Out with Visual Basic.NET 2 nd Edition Lifetime of a Variable The storage for a variable is created upon each use of the procedure The storage for a variable is destroyed as soon as the procedure finishes executing

36 Starting Out with Visual Basic.NET 2 nd Edition Setting a Specific Date This can be done a number of ways: startDate = #12/3/2002 1:00:00 AM# startDate = System.Convert.ToDateTime( "12/3/2002 1:00:00 AM")

37 Starting Out with Visual Basic.NET 2 nd Edition Setting the Current Date/Time A series of keywords yields the date and time or just one or the other: Now startTime = Now TimeOfDay startTime = TimeOfDay Today startTime = Today

38 Starting Out with Visual Basic.NET 2 nd Edition The Val Function, I Suppose you wish to use text input as a number: number = txtInput.Text This will work without a run time error as long as txtInput.Text is the text equivalent of a numerical value (like "45") If it is not, there will be a run time error

39 Starting Out with Visual Basic.NET 2 nd Edition The Val Function, II The Val function is more lenient on conversions from text to numeric values If the initial characters form a numeric value, it will return that Otherwise, it will return a value of zero

40 Starting Out with Visual Basic.NET 2 nd Edition The Val Function, III ArgumentVal(Argument) "34.90" 34.9 "86abc" 86 "$24.95"0 "3,789"3 "" 0 "x29" 0 "47%" 47 "Geraldine" 0

41 Starting Out with Visual Basic.NET 2 nd Edition ToString Method This is a Method that will convert any variable to a string, as in Dim number As Integer = 123 lblNumber.Text = number.ToString

42 Starting Out with Visual Basic.NET 2 nd Edition Option Strict On Placed at the very top of the code window this will prevent Visual Basic.NET from performing implicit data type conversion The code must perform all conversions using Val or ToString (or another similar conversion procedure such as CInt or Integer.Parse)

43 Starting Out with Visual Basic.NET 2 nd Edition 3.4 Performing Calculations and Working With Numbers Visual Basic.NET Provides Several Operators for Performing Mathematical Operations You May Also Use Parentheses to Group Operations and Build More Complex Mathematical Statements

44 Starting Out with Visual Basic.NET 2 nd Edition The Arithmetic Operators, I Visual Basic.NET provides operators for the common arithmetic operations: Addition+ Subtraction- Multiplication* Division/ Exponentiation^

45 Starting Out with Visual Basic.NET 2 nd Edition The Arithmetic Operators, II Examples of use: total = price + tax area = length * width average = total / items salePrice = retail / 2 cubeArea = side ^ 3

46 Starting Out with Visual Basic.NET 2 nd Edition Special Integer Division Operator The backslash (\) is used as an integer division operator The result is always an integer, created by doing the division and then discarding any remainder Any floating-point operand is first rounded to the nearest integer

47 Starting Out with Visual Basic.NET 2 nd Edition Special Modulo (MOD) Operator This operator follows the same basic rules as the backslash operator, but yields the remainder after the division \ operator yields an integer result of division MOD operator yields the integer remainder (after division using the \ operator)

48 Starting Out with Visual Basic.NET 2 nd Edition Arithmetic Operator Precedence, I Which operations are done first -- precedence tells us -- highest to lowest: Exponentiation (^) Multiplicative (* and /) Integer Division (\) Modulus (MOD) Additive (+ and -)

49 Starting Out with Visual Basic.NET 2 nd Edition Arithmetic Operator Precedence, II When two operators with the same precedence share an operand, the operator on the left works first, then the operator on the right

50 Starting Out with Visual Basic.NET 2 nd Edition Arithmetic Operator Precedence, III Grouping with parentheses () forces the expression within those parentheses to be evaluated before others Roughly speaking, the order of evaluation in Visual Basic.NET is similar to that used in algebra (parenthesized expressions first, then exponentiation, then multiplicative operators, then the additive operators)

51 Starting Out with Visual Basic.NET 2 nd Edition Combined Assignment Operators, I Many assignment statements are similar to: number = number - 5 They modify a variable with one arithmetic operator and store the result back into the same variable

52 Starting Out with Visual Basic.NET 2 nd Edition Combined Assignment Operators, II There are special assignment operators to enhance this usage: += add a value to the variable -= subtract a value from the variable *= multiple the variable by some value /= divide the variable by some value \= integer divide the variable by some value &= concatenate the variable with some value

53 Starting Out with Visual Basic.NET 2 nd Edition Type Conversion Functions Cbool Cbyte Cchar Cdate CDbl CDec Cint CLng Cobj Cshort CSng CStr To convert from String to number, it’s best to use Parse, e.g.: Decimal.Parse or Integer.Parse

54 Starting Out with Visual Basic.NET 2 nd Edition Named Constants, I Whenever a program needs to use a constant (e.g., the local sales tax percentage) it is a good idea to give it a variable name However, a variable does not necessarily have the same value throughout the program as an assignment statement can change the value

55 Starting Out with Visual Basic.NET 2 nd Edition Named Constants, II Visual Basic.NET provides for a variable whose value, once established in the declaration, cannot be modified afterwards: Const salesTax As Single = 0.06

56 Starting Out with Visual Basic.NET 2 nd Edition 3.5 Formatting Numbers for Output Numbers May Be Formatted in Various Ways for Output

57 Starting Out with Visual Basic.NET 2 nd Edition FormatNumber Function FormatNumber(expression [, DecimalPoints]) The expression is evaluated and output as a number The optional second argument gives the number of requested decimal places

58 Starting Out with Visual Basic.NET 2 nd Edition FormatCurrency Function FormatCurrency(expression [, DecimalPoints]) The expression is evaluated and output as a currency value based on your PCs local options The optional second argument gives the number of requested decimal places

59 Starting Out with Visual Basic.NET 2 nd Edition FormatPercent Function FormatPercent(expression [, DecimalPoints]) The expression is evaluated and output as a percentage value The optional second argument gives the number of requested decimal places

60 Starting Out with Visual Basic.NET 2 nd Edition FormatDateTime Function FormatDateTime(expression [, Format]) The expression is evaluated and output as a date and time value based on Format The optional second argument gives the requested format, e.g. DateFormat.GeneralDate DateFormat.LongDate Etc.

61 Starting Out with Visual Basic.NET 2 nd Edition 3.6 Group Boxes, Form Formatting, and the Load Event Procedure In This Section We Discuss the GroupBox Control, Which Is Used to Group Other Controls, and How to Align and Center Controls on a Form

62 Starting Out with Visual Basic.NET 2 nd Edition Group Box A Group Box creates a Logical and Physical grouping of controls Physical: They are surrounded by a box and have a title Logical: The controls within the box have a tab ordering within the Group box

63 Starting Out with Visual Basic.NET 2 nd Edition Placing Controls within a Group Box Select the Group Box then double click a control to add to the group, or Select the Group Box then click the desired tool in the toolbox and draw the control inside the Group Box, or Cut a control, select the Group Box, and then paste the control

64 Starting Out with Visual Basic.NET 2 nd Edition Form Formatting, I The form defaults to an 8x8 "snap to" grid This can be modified by going to Tools/Options and then selecting "Windows Forms Designer" Modify the granularity of the grid Show the grid or not Either use "snap to" or not

65 Starting Out with Visual Basic.NET 2 nd Edition Form Formatting, II Multiple controls can be selected simultaneously by: Click and dragging an area and/or Ctrl-Clicking individual objects

66 Starting Out with Visual Basic.NET 2 nd Edition Form Formatting, III Once selected controls may be organized via: Align lefts Align centers Align rights Align tops Align middles Align bottoms

67 Starting Out with Visual Basic.NET 2 nd Edition Form Formatting, IV Other submenu operations include: Same Size Horizontal and Vertical Spacing Center in Form Order

68 Starting Out with Visual Basic.NET 2 nd Edition Load Event Procedure Every form has a Load event procedure It is executed each time the form loads into memory To to execute some code at that time: Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ' Code to be executed when the Form loads End Sub

69 Starting Out with Visual Basic.NET 2 nd Edition 3.8 More About Debugging: Locating Logic Errors Visual Basic.NET Allows You to Pause a Program, Then Execute Its Statements One at a Time After Each Statement Executes, You May Examine Variable Contents and Property Values

70 Starting Out with Visual Basic.NET 2 nd Edition Debugging Problem The program does not work correctly (has one or more logic errors) Running the program with various inputs has not isolated where those logic errors are hiding What can be done?

71 Starting Out with Visual Basic.NET 2 nd Edition Visual Basic.NET Debugging Aids, I Single Step through the program This amounts to executing the program a statement at a time One can then see and examine: What is happening one statement at a time Where it is happening What the various data values are (Watches)

72 Starting Out with Visual Basic.NET 2 nd Edition Visual Basic.NET Debugging Aids, III Related debugging tools include Executing to a breakpoint (placed just before you think the program's logic error may be) Examining the values of expressions


Download ppt "Starting Out with Visual Basic.NET 2 nd Edition Chapter 3 Input, Variables, Constants, And Calculations."

Similar presentations


Ads by Google