Presentation is loading. Please wait.

Presentation is loading. Please wait.

Input Validation Check the values entered into a text box before beginning any calculations Validation is a form of ‘self-protection’, rejecting bad data.

Similar presentations


Presentation on theme: "Input Validation Check the values entered into a text box before beginning any calculations Validation is a form of ‘self-protection’, rejecting bad data."— Presentation transcript:

1 Input Validation Check the values entered into a text box before beginning any calculations Validation is a form of ‘self-protection’, rejecting bad data as a result of ‘user error’ Checking to verify that appropriate values have been entered for a text box is called validation The validation may include checking the type of data, checking for specific values, or checking a range of values

2 Checking the Data Type: IsNumeric Function Used to make sure that the data entered is truly numeric The IsNumeric Function returns ‘True’ or ‘False’ to indicate the result of the value checked IsNumeric(Expression) The function tests whether the value is numeric and therefore can be used in a calculation, therefore helping to avoid problems in procedures that contain calculations

3 If the data cannot be converted to a number, the calculation cannot be performed and a Run-Time Error will occur, which can be prevented by checking the contents of a field after the data has been entered If IsNumeric(txtQuantity.Text) Then iQuantity = Val(txtQuantity.Text) lblDue.Caption = cPrice * iQuantity End If Checking for a Range of Values: Data Validation may also include checking the reasonableness of a value If Val(txtHours.Text) > 10 Then

4 Message Boxes If the value entered by a user is incorrect, then the user can be notified by displaying a Message Box A special type of VB Window in which a message can be displayed to a user Validating input data is an appropriate time to use a message box. If data is rejected, the user needs to be informed as to why the desired action was not achieved Msgbox “Message String”, [Buttons/Icons], “Caption of the Titlebar”

5 The Message String is the message that will appear in the message box The Buttons portion is optional; it determines the command buttons that will be displayed and any icons that will appear If The Caption of Title Bar is omitted, then the project name will appear in the message box title bar Message Boxes can be used as a statement, which displays an ‘OK’ button only, or it can be used a s a function The Message Box Function returns a value indicating which button was pressed

6 Display a message box in the Else clause of an If statement when checking the validity of data If IsNumeric(txtQuantity.Text) Then iQuantity = Val(txtQuantity.Text) lblDue.Caption = cPrice * iQuantity Else MsgBox “Please enter a numeric value”, vbOKonly, “Error” End If

7 Message Box (Function) Msgbox “Message String”, [Buttons/Icons], “Caption of the Titlebar” Function Return Values The MsgBox Function returns a value that can be tested in a condition using a value (numbers 1 through 7) or an associated intrinsic constant Button Specification and/or Icons to Display The user can specify which buttons to display by using numbers or the VB intrinsic constants, to choose the buttons and an icon, use a plus sign to add the 2 values together

8 The Message Box Function (Example) Dim iResponse As Integer iResponse = MsgBox(“Do you wish to continue?”, vbYesNo + vbQuestion, “Continue Processing …..”) If iResponse = vbYes Then Text1.Text = InputBox(“Please enter a value”, “Enter a Value”) Else Text1.Text = “ ” End If

9 Set to Default

10 No Default

11 No Option Selected

12

13

14 InputBox Function Used to request input from the user The InputBox Function consists of a new form that holds a text box The InputBox Function is similar to the MsgBox In an InputBox you can display a message, called a prompt, and allow the user to type input into the text box VariableName = InputBox(“Prompt”, “Title”)

15

16 The Prompt must be enclosed in quotation marks (and may include newline characters vbCrLf, if you want the prompt to appear on multiple lines) The Title displays in the title bar of the dialog box, and if the title is missing, the project name appears in the title bar VariableName = InputBox(“Prompt”, “Title”, Default, XPos, YPos) Any value displayed in Default appears in the text box when it is displayed, otherwise the text box is empty (If string default, then must be enclosed in quotation marks) XPos and YPos, if present, define the measurement in twips (1/1440 of an inch) for the left edge and top edge of the box

17 Format Function Used to format data for display, either on the printer or on the screen Predefined Formats User-Defined (Custom) Formats To Format means to control the way output will be presented to the user For example, 12 is just a number, but $12.00 conveys more meaning as dollar amounts (the currency format is used to display dollar amounts) Format$(ExpressionToFormat, “FormatDescription”)

18 Format$(ExpressionToFormat, “FormatDescription”) The optional dollar sign in the function name specifies that the formatted value will be a string, without the dollar sign, the value returned is a variant data type In most cases the results will be the same, but the use of the dollar sign is much more efficient, Why? The expression to be formatted maybe numeric or string, a variable, a literal, or a property. In most cases formats are used for numeric data, to control the number of decimal positions Formats are not generally needed for integer values

19 The format description can take one of several forms VB provides several predefined formats for the most common types of output To select one of these formats, include the format name in quotation marks lblTotal.Caption = Format$(cTotalAmount, “Currency”) A feature of the format function, is that it rounds fractional values to the requested number of decimal places The value is rounded for output, but the stored value does not change, and any further calculations, using the value, will be done with the non-rounded (stored)value

20 If the Predefined Formats do not give the results that you want, you can create your own Custom Formats To help in creating these formats, use the Help Topics provided by VB for: User-Defined Formats

21 With..End With Statements There are times when several Properties or Methods of a single Control (Object) need to be changed (modified) In previous versions of VB, the programmer had to write out the entire name of the Object along with its Properties or Methods for each statement, in which the changes were required (Object.Property or Object.Method) These statements can still be specified in this way, however, VB now provides a statement to make this task much easier and efficient, and make projects execute faster - the With..End With statement

22 When the ObjectName is specified in the With statement, all subsequent statements, (relating to Properties and/or Methods), until the End With relate to that specific Object With Text1.Text = “ ”.Visible = True.ForeColor = vbWhite.SetFocus End With With ObjectName Statement(s) End With With Check1.Enabled = True.Value = False End With With Block Method

23 Concatenating Strings Sometimes there is a requirement to join strings of text For example, you may need to join a String Literal (which may be stored in a Variable of a String Data Type), to the value stored in the Property of an Object You can ‘Tack’ one string of characters to the end of another, in the process called Concatenation Use an Ampersand sign (&), preceded and followed by a space, between the 2 strings (Literals or Properties) being joined

24 lblMessage.Caption = “Your Name is: ” & txtName.Text txtNameAndAddress.Text = txtName.Text & txtAddress.Text lblFontSize.Caption = “The current fontsize is: ” & txtMessage.Font.Size & “ points.” Line-Continuation Character If a VB Statement gets too long for one line, then a Line- Continuation Character may be used (Type a Space and an Underscore, and then press Enter, and continue coding the statement on the next line) The only restriction is that the line-continuation character must appear between elements, it cannot appear in the middle of a literal or split the name of an object or property

25

26 Controls and their Default Properties Each class of control has one property that is the Default Property When you use the Default Property of a control, you do not have to name that property For example, the Text property is the Default Property of the Text Box control, therefore, these 2 statements are equivalent: txtName.Text = InputBox(“Enter the Name”, “User Input”) txtName = InputBox(“Enter the Name”, “User Input”) This may not be advisable, therefore, use the complete form (Text1.Text) for Consistency, Readability, and Understandability in the code

27 Constants - Named and Intrinsic Constants describe a value that does not change (static) throughout the execution of a project Constants that are built into VB are called: Intrinsic Constants and don’t have to be defined anywhere Constants that the programmer defines are called: Named Constants

28 Intrinsic Constants System-Defined Constants Several sets of intrinsic constants are stored in library files and available to use in VB Colour Constants: vbRed; vbBlue; etc…. Message Icons: vbInformation; vbExclamation; etc….

29 Named Constants Declare named constants with the keyword Const Give the constant a Name, a Data Type, and a Value Const Identifier As Data Type = Value The Data Type that is declared and the Data Type of the value must match If you declare an Integer Data Type, it must be assigned as Integer Value

30 Constants use Uppercase characters separated by Underscores (for distinction); in that it is identified as a constant throughout the code, and cannot be assigned any other value than that to which it has been declared Constants make code more Understandable and Maintainable Furthermore, to change the value of a constant, change the constant declaration only once, and there is no need to change the reference to the constant throughout the code

31 Const cMAXIMUM_PAY As Currency = 450.00 Const iTOTAL_NUMEMPLOYEES As Integer = 200 Although the Data Type is optional, the best practice is always to declare a Data Type When a Data Type is not declared, VB looks at the Value given in the Const declaration and chooses an appropriate Data Type (How does this differ from a variable declaration?) The scope at which the constant is defined determines the scope of the constants value across the project

32 Scope of Variables and Constants A Variable or Constant may exist and be Visible for an entire project, for only one form, or for only one procedure Therefore, the visibility of a variable or constant is referred to as its Scope Visibility means that “can this variable be seen” in this location The scope of a variable or constant is said to be Global, Module (Form) Level, or Local

33 Module Level variables or constants are accessible from all procedures of a Form A Local variable or constant may be used only within the procedure in which it is declared The Scope of a Variable declared with a DIM statement is determined by where the declaration statement is made The Lifetime of a Variable is the period of time that the variable exists The Lifetime of a Local variable is normally one execution of the procedure The Lifetime of a Module Level variable is the entire time the Form is Loaded (generally the lifetime of the entire project)

34

35

36 Multi-Form Projects Working with more than one form in a project The first form that VB displays is called the STARTUP FORM To add another form; Project Menu/Add Form or select the icon from the shortcut toolbar This form will be added to the project, and cam be viewed from the Project Explorer Window

37 Each form is a separate entity, and the code exists and is related only to the specific form To move between each form: FORMNAME.SHOW FORMNAME.HIDE

38 Finding and Fixing Errors 3 varieties of programming errors Compile Errors Run-Time Errors Logic Errors Compile Errors: As VB attempts to convert the project code to machine language (known as compiling the code) it identifies any compile errors Compile errors occur when the syntax rules of Basic are violated or illegal objects or properties are used (eg: incorrect spelling/incorrect punctuation)

39 Run-Time Errors: if the project halts during execution, it is a run-time error VB displays a Dialog Box, goes into break time, and highlights the statement causing the problem Statements that cannot execute correctly cause run-time errors The statements do not cause compile errors, however the statements fail to execute, which can be caused by attempting to do impossible arithmetic operations such as calculate with nonnumeric data, divide by zero, or find the square root of a negative number

40 Logic Errors: the project runs but produces incorrect results (eg: the results of a calculation are incorrect, or the wrong text appears, or the text is okay but appears in the wrong location) Involves checking all aspects of the project output: - Computations - Text - Spacing

41 Finding and fixing program ‘bugs’ is called Debugging Compile and Run-Time errors are identified by VB Logic errors have to located by the programmer Industry standard naming conventions for VB objects, if adhered to, make projects more understandable A Prefix followed by the name of the object lblMessage cmdExit

42 The IDE (Integrated Development Environment) provides a DEBUGGER for locating and correcting errors in program logic (logic errors not syntax errors) The debugger is typically used to: Trace Program Control Examine Variable Values Validate Program Input and Output The debugger can only be used in IDE BREAK MODE Debugging in Visual Basic

43 Forcing a Break During the debugging process, you may want to stop at a particular location in code and watch what happens which branch of an If..Then..Else statement is executed which procedures were executed the value of a variable just before or after a calculation Force the project to break by inserting a break-point in code

44 To set a breakpoint, place the cursor in the grey margin indicator area at the left edge of the code window and click The line will be highlighted in red and a large red dot will be displayed in the margin indicator margin indicator or

45 After setting the breakpoint, start/restart program execution When the project reaches the breakpoint, it will halt, display the line at which the breakpoint is set, and go into break time To turn off a breakpoint, click on either Toggle Breakpoint or Clear All Breakpoints from the Debug Menu To turn off a breakpoint, simply click on the red dot in the grey margin indicator area alternatively

46 Using the Immediate Window The immediate window is available at design time, run time, and break time The values of data or messages can be displayed in the immediate window while the project is executing In break time, the immediate window can be used to view or change the current contents of variables or to execute lines of code At design time, view the window to see values from the previous run, but you cannot execute any code

47 Checking the Current Values of Expressions

48 Debug Toolbar Debug Menu

49 Start Step Out Toggle Breakpoint Watch Window Locals Window Break End Step Into Step Over Quick Watch Call Stack Immediate Window

50 Step Into Executes the current line. If the current line is a procedure or function call, the procedure or function code is entered Step Over Executes the current line. If the current line is a procedure or function call, the procedure or function is executed without stepping into its code Step Out Execute the remaining procedure or function code and continue stepping through the procedure or function caller’s code Run To Cursor Executes all lines of code up to the line containing the cursor Add Watch Displays the Add Watch dialog Edit Watch Displays the Edit Watch dialog Quick Watch Displays the Quick Watch dialog Toggle Breakpoint Adds or removes a breakpoint Clear All Breakpoints Removes all breakpoints Set Next Statement Allows the programmer to specify which statement within the procedure or function is executed next Show Next Statement Transfers the cursor to the next line to be executed

51 The debugging tools can help find and eliminate logic and run-time errors The debugging tools can help to follow the logic of a project to better understand how it works Debugging in Visual Basic

52 Code relating to the click events of the option buttons

53

54

55


Download ppt "Input Validation Check the values entered into a text box before beginning any calculations Validation is a form of ‘self-protection’, rejecting bad data."

Similar presentations


Ads by Google