Chapter 6 Sub Procedures

Slides:



Advertisements
Similar presentations
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 6- 1 STARTING OUT WITH Visual Basic 2008 FOURTH EDITION Tony Gaddis.
Advertisements

Subprograms Functions Procedures. Subprograms A subprogram separates the performance of some task from the rest of the program. Benefits: “Divide and.
Sub and Function Procedures
The Web Warrior Guide to Web Design Technologies
Chapter 7: Sub and Function Procedures
Microsoft Visual Basic 2010: Reloaded Fourth Edition Chapter Eight Sub and Function Procedures.
1.
Chapter 5 Menus, Common Dialog Boxes, Sub Procedures, and Function Procedures Copyright © 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved.
IS 1181 IS 118 Introduction to Development Tools VB Chapter 06.
VBA Modules, Functions, Variables, and Constants
Chapter 7: Sub and Function Procedures
Chapter 4 - Visual Basic Schneider1 Chapter 4 General Procedures.
Chapter 41 General Procedures Sub Procedures, Part I Sub Procedures, Part II Function Procedures.
Slide 1 Chapter 2 Visual Basic Interface. Slide 2 Chapter 2 Windows GUI  A GUI is a graphical user interface.  The interface is what appears on the.
Microsoft Visual Basic 2005 CHAPTER 8 Using Procedures and Exception Handling.
Chapter 5 new The Do…Loop Statement
Apply Sub Procedures/Methods and User Defined Functions
Tutorial 7: Sub and Function Procedures1 Tutorial 7 Sub and Function Procedures.
Programming with Microsoft Visual Basic 2012 Chapter 7: Sub and Function Procedures.
© 2006 ITT Educational Services Inc. Introduction to Computer Programming: Unit 1: Chapter 2: Slide 1 Unit 1 Introduction to Programming Using VB.NET Chapter.
© 2007 Lawrenceville Press Slide 1 Chapter 7 Top-Down Development  Problem-solving approach  Breaking a task down into smaller subtasks  First level.
Using Data Active Server Pages Objectives In this chapter, you will: Learn about variables and constants Explore application and session variables Learn.
Microsoft Visual Basic 2012 Using Procedures and Exception Handling CHAPTER SEVEN.
XP New Perspectives on Microsoft Office Access 2003 Tutorial 11 1 Microsoft Office Access 2003 Tutorial 11 – Using and Writing Visual Basic for Applications.
Tutorial 11 Using and Writing Visual Basic for Applications Code
CHAPTER SIX Reducing Program Complexity General Sub Procedures and Developer-defined Functions.
CHAPTER SIX Reducing Program Complexity General Sub Procedures and Developer-defined Functions.
© 2006 Lawrenceville Press Slide 1 Chapter 3 Visual Basic Interface.
McGraw-Hill © 2009 The McGraw-Hill Companies, Inc. All rights reserved. Chapter 5 Menus, Common Dialog Boxes, Sub Procedures, and Function Procedures.
Chapter 3 – Fundamentals of Programming in VB.NET VB.NET Controls VB.NET Events Numbers Strings Input and Output.
Starting Out with Visual Basic.NET 2 nd Edition Chapter 2 Creating Applications With Visual Basic.NET.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Visual Basic.NET Comprehensive Concepts and Techniques Chapter 7 Using Menus, Common Dialogs, Procedures, Functions, and Arrays.
Program Design and Coding
Microsoft Visual Basic 2012 CHAPTER THREE Program Design and Coding.
Microsoft Visual Basic 2010 CHAPTER THREE Program Design and Coding.
© 2012 EMC Publishing, LLC Slide 1 Chapter 8 Arrays  Can store many of the same type of data together.  Allows a collection of related values to be stored.
Microsoft Visual Basic 2005: Reloaded Second Edition Chapter 7 Sub and Function Procedures.
The PictureBox Control Prefix Prefix – pic Image Property PictureBox Image Property – Changes the image or file that appears inside of the PictureBox SizeMode.
Object-Oriented Application Development Using VB.NET 1 Chapter 6 Writing a Problem Domain Class Definition.
IMS 3253: Subroutines 1 Dr. Lawrence West, MIS Dept., University of Central Florida Topics Procedures Subroutines Parameters –By Value.
7 1 User-Defined Functions CGI/Perl Programming By Diane Zak.
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
Chapter 4 - Visual Basic Schneider1 Chapter 4 General Procedures.
© 2006 ITT Educational Services Inc. Introduction to Computer Programming: Unit 10: Chapter 6: Slide 1 Unit 10 Sub Procedures and Functions Chapter 6 Sub.
Chapter 2: Variables, Functions, Objects, and Events JavaScript - Introductory.
PROGRAMMING IN VISUAL BASIC.NET VISUAL BASIC PROGRAMMING FUNDAMENTALS Bilal Munir Mughal 1 Chapter-8.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.1.
JavaScript, Fourth Edition
CHAPTER SIX Reducing Program Complexity General Sub Procedures and Developer-defined Functions.
Microsoft Visual Basic 2005 BASICS Lesson 3 Events and Code.
Week Procedures And Functions 7 A procedure is a collection of statements that performs a task.
Creating Menus Menu Bar – behaves like standard Windows menus Can be used in place of or in addition to buttons to execute a procedure Menu items are controls.
Controlling Program Flow with Decision Structures.
Starting Out with Visual Basic.NET 2 nd Edition Chapter 6 Sub Procedures And Functions.
 ASP.NET provides an event based programming model that simplifies web programming  All GUI applications are incomplete without enabling actions  These.
Copyright © 2014 Pearson Education, Inc. Chapter 6 Procedures and Functions.
COM148X1 Interactive Programming Lecture 8. Topics Today Review.
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.
© 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.
Sub Procedures And Functions
Programming Right from the Start with Visual Basic .NET 1/e
A variable is a name for a value stored in memory.
Chapter 7 Top-Down Development
Microsoft Access Illustrated
Using Procedures and Exception Handling
Chapter 6 Sub Procedures
CIS16 Application Development and Programming using Visual Basic.net
Presentation transcript:

Chapter 6 Sub Procedures 4/24/2017 12:42 AM Chapter 6 Sub Procedures A set of statements that perform a specific task. Divide a program into smaller, more manageable blocks of code-> “Divide et impera” = “Divide and conquer” An event procedure is written for a specific object event, while a sub procedure can perform tasks unrelated to any specific event. Procedure names should begin with an uppercase letter and then an uppercase letter should begin each word within the name. May not contain spaces. Executed by using a Call statement. Syntax: Sub ProcedureName() statements End Sub Interactive/Advantages: - Divide a program into smaller, more manageable blocks of code. Less code redundancy because statements for a specific task appear just once in the Sub procedure More flexible because changes to statements for a task need only be made in the sub procedure Procedures can be Private ( cannot be accessed outside Form1 class) or Public ( accessed from other Form objects ). Procedures need a trigger to get executed: Event Call © 2012 EMC Publishing, LLC

Chapter 6 The PictureBox Control 4/24/2017 12:42 AM Chapter 6 The PictureBox Control (Name) should begin with pic. Image is used to add images to the Resource folder with the selected image displayed in the picture box. SizeMode is typically set to AutoSize so that the picture box is automatically sized to the image size. Visible is set to False to hide an image at run time. Size changes automatically when SizeMode is AutoSize. A Click event procedure is sometimes coded for a picture box. It executes when user clicks image. Image contains button that is clicked to display the Select Resource dialog. In this dialog images can be added to the Resources folder of a project and an image can be selected for a picture box. Once image is added to the Resource folder, it is available for any picture box on the form. Types: BMP, JPG, GIF, PNG and WMF formats To remove picture from picture box: right-click and select Reset The form’s background color is changed using the BackColor property © 2012 EMC Publishing, LLC

Chapter 6 Changing an Image at Run Time 4/24/2017 12:42 AM Chapter 6 Changing an Image at Run Time Images must be stored in the Resources folder in the project folder. The My.Resources object is used to access an image at run time: My.pictureBox.Image = My.Resources.imageName © 2012 EMC Publishing, LLC

Chapter 6 The LinkLabel Control 4/24/2017 12:42 AM Chapter 6 The LinkLabel Control The LinkLabel Control is used to add a link to a website (Name) id for programmer. Prefix: lnk ActiveLinkColor sets the color of the link when clicked LinkColor sets the color of the link. Text sets the text for the destination website. VisitedLinkColor sets the color of a previously visited link Write PetStore. Clicking on the link does not do anything until: Create a Click event procedure for the lnkName object Add in the procedure System.Diagnostics.Process.Start("http://www.google.com"). Because of this I can change the Text property of the LinkLabel to anything else ( like Google for example ) and it still connects to the web site. Result: Private Sub lnklvp_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles lnklvp.LinkClicked System.Diagnostics.Process.Start("http://www.google.com”) End Sub © 2012 EMC Publishing, LLC

Chapter 6 Value Parameters A procedure can have parameters for accepting values from a calling statement. Parameters are used inside the procedure to perform the procedure's task. Data passed to a procedure is called the arguments. Call ProcedureName(parameter1, parameter2) … Sub ProcedureName(ByVal parameter1 As type, ByVal parameter2) Statements End Sub ByVal indicates that the parameter is a value parameter. A value parameter is only used as a local variable by the called procedure. That means that after the procedure has executed, the value of the variable/argument in the procedure call has not changed. There can be many parameters separated by commas. © 2012 EMC Publishing, LLC

Chapter 6 Value Parameters (cont.) The order of the arguments passed corresponds to the order of the parameters in the procedure heading. The number of arguments in a procedure call must match the number of parameters in the procedure declaration. Arguments passed by value can be in the form of constants, variables, values, or expressions. Variable arguments passed by value are not changed by the procedure. Example( create Form with 1 label = lblNumber and 1 button = btnRun ): Private Sub btnRun_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRun.Click Dim counter As Integer = 1 Call ShowCount(counter) Me.lblNumber.Text = counter 'Displays 1 End Sub Sub ShowCount(ByVal counter As Integer) ‚=> it can be used a different name for the variable counter += 1 MessageBox.Show(counter) 'Displays 2 It demonstrates that counter in ShowCount() has no relation to counter in Demo(). It displays first the MessageBox counter=2. After it displays Me.lblNumber.Text counter=1 © 2012 EMC Publishing, LLC

Chapter 6 Procedure Documentation 4/24/2017 12:42 AM Chapter 6 Procedure Documentation Procedure documentation should include a brief description of what the procedure does. Documentation should also include the assumptions, or initial requirements, of a procedure called preconditions (pre:). Documentation should include a postcondition (post:), which is what must be true at the end of the execution of a procedure if the procedure has worked properly. Comments with functionality and pre: and post: conditions. Show as example TestBuild © 2012 EMC Publishing, LLC

4/24/2017 12:42 AM Reference Parameters A procedure can use reference parameters to send values back to the calling procedure. Reference parameters can alter the variables used in the procedure call Syntax: Sub ProcedureName(ByRef parameter1 As type,…) Statements End Sub A procedure can have both reference (ByRef) and value (ByVal) parameters. Example/Console: ‘The digits of a two-digit number are returned in separate parameters ‘pre: num is a number less than 100 and greater than 0 ‘post: firstDigit stores a number between 0 and 9 inclusive ‘secondDigit stores a number between 0 and 9 inclusive Sub Main() Dim num As Integer = 25 Dim firstDigit, secondDigit As Integer Call TwoDigits(num, firstDigit, secondDigit) Console.WriteLine(num) Console.WriteLine(firstDigit) Console.WriteLine(secondDigit) End Sub Sub TwoDigits(ByVal num As Integer, ByRef firstDigit As Integer, ByRef secondDigit As Integer) firstDigit = num \ 10 secondDigit = num Mod 10 © 2012 EMC Publishing, LLC

Chapter 6 Reference Parameters (cont.) When procedures are called the ByVal parameter is assigned a new memory location and a copy of its value is stored => it does not change the original When ByRef parameters are used the memory address of the original is passed => it changes the original © 2012 EMC Publishing, LLC

Chapter 6 Reference Parameters (cont.) The order of the arguments passed corresponds to the order of the parameters in the procedure heading. ByRef parameters accept only variable arguments. Variable arguments passed by reference may be changed by the procedure. Call ProcedureName(5,1) ‘because ByRef parameters must be variables a run-time error will be generated © 2012 EMC Publishing, LLC

Chapter 6 Control Object Parameters Control objects are a data type called a control class. A control object can be passed as an argument to a procedure. Example: Call GiveHint(Me.lblMessage, secretNumber, guess) Control argument parameters should be declared ByRef in a procedure using the appropriate class name. Control objects: CheckBox, Label, RadioButton, Button, TextBox and PictureBox. Control Class has a visual element that is displayed on the Form and properties for storing data. !!! A procedure can be written without actually knowing the names of the objects on the form. Only the Call statement specifies the real name of the object ( lblHint in the example ) and in the procedure I can use a different name ( generic: lblTip in the example ). Ex(Form1 with 1 x Label=lblHint and 1 x Button=btnTest ): Private Sub btnTest_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTest.Click Dim firstNum, secondNum As Integer firstNum = 5 secondNum = 10 Call GiveHint(lblHint, firstNum, secondNum) End Sub ‘Determines if firstNum is larger than secondNum and then displays an appropriate message ‘post: A message has been displayed in a label. Sub GiveHint(ByRef lblTip As Label, ByVal firstNum As Integer, secondNum As Integer) If firstNum > secondNum Then lblTip.Text = “First is higher.” Else lblTip.Text = “First is lower.” End If © 2012 EMC Publishing, LLC

Chapter 6 Event Handler Procedures 4/24/2017 12:42 AM Chapter 6 Event Handler Procedures Execute in response to events Can be written to handle more than one event. Procedure name can be changed because the events after the Handles keyword is what indicates when the procedure will execute. © 2012 EMC Publishing, LLC

Chapter 6 Event Handler Procedures 4/24/2017 12:42 AM Chapter 6 Event Handler Procedures Event procedures always include 2 parameters: sender and e sender = the object that raised the event. Data type is Object that can be used to represent any value e = info about the event. Data type is System.EventArgs An Event Procedure can handle multiple events (event names separated by commas added after the Handles keyword) Example: Public Class Form1 ‘updates the price of a hot dog ‘post: The hot dog price has been updated in the label Private Sub Topping_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles chkRelish.Click, chkKraut.Click, chkCheese.Click Const TOPPING_PRICE As Double = 0.25 Static price as Double = 2 ‘hot dog base price declared as Static so it does not get reinitialized Dim chkSelectedTopping As CheckBox = sender ‘object that raised event If chkSelectedTopping.Checked Then price += TOPPING_PRICE Else price -= TOPPING_PRICE End If Me.lblCurrentPrice.Text = “Price: $” & price ‘Display updated price End Sub End Class © 2012 EMC Publishing, LLC

Chapter 6 The HotDog Application 4/24/2017 12:42 AM Chapter 6 The HotDog Application The procedure name was changed to a more generic name ( from chkRelish_Click to Topping_Click ) Additional events to be handled by the procedure were typed after Handles keyword Sender was assigned to a CheckBox variable so that his properties can be accessed © 2012 EMC Publishing, LLC

Chapter 6 The Tag Property 4/24/2017 12:42 AM Chapter 6 The Tag Property Every control has a Tag property. Can be set to a string that is useful for identifying the object. When an event procedure is handling more than one object, the string in the Tag property can be used to determine which object raised the event. The Tag property is set to a descriptive string and its value is used to determine which action to take. Example(HotDog modified-> modify Tag for all 3 checkboxes: Relish, Kraut, Cheese. If not modified no error but price stays $2 ) Public Class Form1 ‘updates the price of a hot dog ‘pre: sender has valid Tag expression ‘post: The hot dog price has been updated in the label Private Sub Topping_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles chkRelish.Click, chkKraut.Click, chkCheese.Click Const RELISH As Double = 0.15 Const KRAUT As Double = 0.25 Const CHEESE As Double = 0.50 Static price as Double = 2 Dim chkSelectedTopping As CheckBox = sender If chkSelectedTopping.Checked Then Select Case chkSelectedTopping.Tag Case “Relish” price += RELISH Case “Kraut” price += KRAUT Case “Cheese” price += CHEESE End Select Else price -= RELISH price -= KRAUT price -= CHEESE End If Me.lblCurrentPrice.Text = “Price: $” & price ‘Display updated price End Sub End Class © 2012 EMC Publishing, LLC

Chapter 6 Function Procedures 4/24/2017 12:42 AM Chapter 6 Function Procedures A set of statements that perform a specific task and then return a value. Built-in functions include Int() and Rnd(). Syntax: Function ProcedureName(ByVal parm1 As type…) As Returntype statements Return value End Function There can be many parameters separated by commas Returntype indicates the data type of the value returned by the function There can be more than one Return but the function ends after the first Return statement executes Example: MHS\CompSci I\PROGRAMS IN TEXT\Letter Grade\Letter Grade 'BC: 08/01/13-> Ch_6/Review7: Letter Grade See code bellow: Private Sub btnLetterGrade_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnLetterGrade.Click Const sngLOWESTSCORE As Single = 0 Const sngHIGHESTSCORE As Single = 100 Dim sngScoreEntered As Single sngScoreEntered = Val(Me.txtScore.Text) If Not ValidEntry(sngScoreEntered, sngHIGHESTSCORE, sngLOWESTSCORE) Then MessageBox.Show("Enter a score between " & sngLOWESTSCORE & "and" & sngHIGHESTSCORE) Me.txtScore.Text = Nothing Me.lblLetterGrade.Text = Nothing Else Me.lblLetterGrade.Text = "Your grade is " & LetterGrade(sngScoreEntered) End If End Sub '```````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````` 'Returns True if intLowerLimit <= intUserNum <= intUpperLimit ' 'post: True returned if intLowerLimit <= intUserNum <= intUpperLimit 'otherwise False returned Function ValidEntry(ByVal intUserNum As Integer, ByVal intUpperLimit As Integer, ByVal intLowerLimit As Integer) As Boolean If intUserNum > intUpperLimit Or intUserNum < intLowerLimit Then Return False Return True End Function '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 'Returns a letter grade corresoonding to sngScore 'post: a letter grade has been returned Function LetterGrade(ByVal sngScore As Single) As Char If sngScore >= 90 Then Return "A" ElseIf sngScore >= 80 Then Return "B" ElseIf sngScore >= 70 Then Return "C" ElseIf sngScore >= 60 Then Return "D" Return "F" End Class © 2012 EMC Publishing, LLC

Chapter 6 Function Procedures 4/24/2017 12:42 AM Chapter 6 Function Procedures A function often has at least one parameter for data that is required to perform its task. Parameters are ByVal because a function returns a single value without changing argument values. Called from within an assignment statement or another type of statement that will make use of the returned value. A function is a better choice over a Sub procedure when a well-defined task that results in a single value is to be performed The order of arguments corresponds to the order of parameters Only ByVal parameters should be declared in a function because functions should not alter the arguments it has been passed A function returns a single value and therefore must be used in a statement such as an assignment statement that makes use of the returned value. © 2012 EMC Publishing, LLC