Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 6 Sub Procedures

Similar presentations


Presentation on theme: "Chapter 6 Sub Procedures"— Presentation transcript:

1 Chapter 6 Sub Procedures
4/24/ :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

2 Chapter 6 The PictureBox Control
4/24/ :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

3 Chapter 6 Changing an Image at Run Time
4/24/ :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

4 Chapter 6 The LinkLabel Control
4/24/ :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(" 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(" End Sub © 2012 EMC Publishing, LLC

5 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

6 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

7 Chapter 6 Procedure Documentation
4/24/ :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

8 4/24/ :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

9 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

10 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

11 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

12 Chapter 6 Event Handler Procedures
4/24/ :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

13 Chapter 6 Event Handler Procedures
4/24/ :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 = ‘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

14 Chapter 6 The HotDog Application
4/24/ :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

15 Chapter 6 The Tag Property
4/24/ :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

16 Chapter 6 Function Procedures
4/24/ :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

17 Chapter 6 Function Procedures
4/24/ :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


Download ppt "Chapter 6 Sub Procedures"

Similar presentations


Ads by Google