Programming with Microsoft Visual Basic.NET
Tutorial 7
Sub and Function Procedures
Lesson A: Creating Sub and Function Procedures
Lesson B: Using a List Box Control
Lesson C: Completing the Payroll Application
Instructor’s Notes
Overview
Outline
Objectives
Lecture Notes
Discussion Topics
Extra Projects
Key Terms
Overview
Procedures are the containers of all program code statements. Declarations may occur outside a procedure but not statements. Lesson A addresses creating user-defined Sub and Function procedures, passing parameters and returning data. Lesson B introduces the list box control. Lesson C introduces multi-form projects and the use of Sub Main.
NOTE:Here are some significant changes: arguments are now passed ByVal as the default. In prior versions of Visual Basic, arguments were passed ByRef as the default. A function now uses the Return statement to set the value. When the Return statement is hit, the function next terminates. GoSub is also gonzo.
Outline
Lecture Topics / Pages # / Teaching Suggestions in this ManualCreating Sub and Function procedures / 435-446 / Creating Sub and Function Procedures
Using a List Box Control / 452-473 / Using a List Box Control
Completing the Payroll Application / 478-484 / Completing the Payroll Program
Creating Sub and Function Procedures
Lesson A Objectives:
After completing this lesson, you will be able to:
- Explain the difference between a Sub procedure and a Function procedure
- Create a procedure that receives information passed to it
- Explain the difference between passing data by value and by reference
- Create a Function procedure
Lecture Notes
Procedures
A procedure is a block of program code that performs a specific task. Procedures in Visual Basic .NET can be either Sub procedures or Function procedures. The difference between both types of procedures is that a Function procedure returns a value after performing its assigned task, whereas a Sub procedure does not return a value.
Sub Procedures
There are two types of Sub procedures in Visual Basic .NET: event procedures and user-defined Sub procedures. An event procedure is simply a Sub procedure that is associated with a specific object and event, such as a button’s Click event or a text box’s KeyPress event. A user-defined Sub procedure is independent of any object and event, and is processed only when called, or invoked, from code. You invoke a user-defined Sub procedure using the Call statement.
A program is composed of one or more files. A form is contained in a file. You can use different kinds of files to compose a program. Each type of Visual Basic .NET file has the common set of characteristics. Most will contain data and procedures. The only place you can write code is in a procedure. Outside a procedure, the only thing you can use is a defined module-level data.
You will learn about Sub and Function procedures and when to use one over the other. Also, you will learn how to pass data (called parameters) to a procedure and what is the difference between passing a parameter by value or by reference
There are two types of Sub procedures in Visual Basic .NET: event procedures and user-defined Sub procedures. Most of the procedures that you coded in previous tutorials were event procedures. An event procedure is simply a Sub procedure that is associated with a specific object and event, such as a button’s Click event or a text box’s KeyPress event. Recall that the computer automatically processes an event procedure when the event occurs.
NOTE:In Visual Basic .NET, all procedures are the result of an event. All user-defined procedures are called from an event procedure. Even if you use Sub Main, that event is starting the program.
Event Procedures
All event procedures contain two parameters: sender and e.
- sender – Contains the internal memory address of the object that raised the event
- e – Contains any additional information provided by the object.
The fact that sender is the object enables the Handles whereby an event procedure can be made to work for any number of objects, and you can ask which object raised the event.
The KeyPress event, for example, has the properties e.KeyChar and e.Handled. The KeyChar property contains the character corresponding to the key that was pressed, and the Handled property determines whether the text box accepts the key contained in the KeyChar property.
Recall what a Button’s Click event procedures looks like.
- Private means that the scope of the procedure is limited to the form class in which it is contained.
- Sub identifies the type of procedure. Note: The word Sub comes as an abbreviation for subroutine or subprogram, depending upon whom you ask
- ExitButton is the name of the button object
- Click is the event. ExitButton_Click is the name of the event. All events are initially created by concatenating the object name with the event name
- All procedures in a class must have unique names
- A list of parameters is contained within parenthesis
- End Sub denotes the end of the procedure
Including Parameters in a User-Defined Sub Procedure
User-defined Sub procedures all follow the same pattern as Event procedures.
- Procedure header identifies the start of the procedure and names the procedure and identifies any parameters
- The end of the procedure is denoted by End Sub
- Accessibility identifies the scope of the procedure, that is, where can this procedure be access from. Accessibility can be Private, Public, Protected, Friend, or Protected Friend
- Name identifies the procedure name and must be unique in a class
- Optionally, parameters can be passed to the procedure
Private indicates that only the procedures in the current form can access the procedure. Public is used when you want to allow unlimited access to the procedure. Creating Sub procedures using the keyword Protected, Friend, or Protected Friend is beyond the scope of this book.
Between the Sub Header and the End Sub is where you enter program statements that you want this procedure to execute.
It is a common practice to begin a procedure’s name with a verb.
The parameterlist lists the data type and name of memory locations used by the procedure to store the information passed to it. The parameterlist also specifies how each item of information is passed—either by value or by reference. We will discuss what this means shortly.
You can use the Call statement to call (or invoke) a Sub procedure. The syntax of the Call statement is:
Call procedurename([argumentlist])
Where procedurename is the name of the procedure you are calling, and argumentlist (which is optional) is a comma-separated list of arguments you want passed to the procedure. The number of arguments listed in the Call statement’s argumentlist must agree with the number of parameters listed in the parameterlist in the procedure header and the data types of the parameters must match.
NOTE:One change for Visual Basic .NET is that the argument list must be in parentheses. Even if there are no arguments, you must include the parentheses.
Visual Basic .NET allows you to specify that an argument in the Call statement as optional. If the argument is not provided, a default value is used for the corresponding parameter in the parameterlist.
You can pass a literal constant, named constant, keyword, or variable to a user-defined Sub procedure. In most cases, you will pass a variable.
Passing Variables
Each variable you declare in an application has both a value and a unique address that represents the location of the variable in the computer’s internal memory. Visual Basic .NET allows you to pass either the variable’s value (referred to as passing by value) or its address (referred to as passing by reference) to the receiving procedure. The method you choose—by value or by reference—depends on whether you want the receiving procedure to have access to the variable in memory—in other words, whether you want to allow the receiving procedure to change the contents of the variable.
NOTE:Passing by reference means that the address is passed. If the content of the variable at that address is modified, the calling procedure has access to the modified content.
By default, variables are passed by value in Visual Basic .NET.
WARNING:If you are migrating from Visual Basic 6, the default for passing parameters was by reference. This creates the possibility for errors. Even though ByVal is the default, it is good programming practice to always specify how a parameter is passed.
For example, if you have a procedure to calculate the pay from the number of hours and the hourly rate, and want to return the pay, you pass the hours and rate by value because you do not want the data changed. The pay is passed by reference so that you can use the resultant value.
Function Procedures
A Function procedure, typically referred to simply as a function, is a block of code that performs a specific task. However, unlike a Sub procedure, a function returns a value after completing its task. Some functions, such as the Val and InputBox functions, are intrinsic to Visual Basic .NET. You can create your own functions, referred to as user-defined functions, in Visual Basic .NET and then invoke it from one or more places in the application. You invoke a user-defined function in exactly the same way as you invoke a built-in function—simply by including the function’s name in a statement. You can pass information to a user-defined function, and the information can be passed either by value or by reference.
Functions typically are called from statements that display the function’s return value, use the return value in a calculation, or assign the return value to a variable.
Function procedures have both a procedure header and procedure footer. The procedure header for a Function procedure is almost identical to the procedure header for a Sub procedure, except it includes the keyword Function rather than the keyword Sub. The keyword Function identifies the procedure as a Function procedure—one that returns a value after completing its task and includes the Asdatatype clause indicating the type of data being returned.
Between the procedure header and the procedure footer, you enter the instructions you want the computer to process when the function is invoked. In most cases, the last statement in a Function procedure is Returnexpression, where expression represents the one and only value that will be returned to the statement that called the function. The data type of the expression in the Return statement must agree with the data type specified in the Asdatatype clause in the procedure header. The Return statement exits the function after returning the value of its expression.
You can have as many Return statements as needed. For example, you might have a selection structure that determines what value to Return.
Quick Quiz
- In a Sub procedure, to return a calculated value, how would you declare the variable in the Sub? ANSWER: To return a value, pass the variable ByRef.
- How is data returned from a Function? ANSWER: Use the Return value statement.
- To calculate a salesperson’s bonus, what type of procedure would you use? ANSWER: Generally, to return a calculated amount, a Function is used.
Using a List Box Control
Lesson B Objectives:
After completing this lesson, you will be able to:
- Add a list box to a form
- Add items to a list box
- Sort the contents of a list box
- Select a list box item from code
- Determine the selected item in a list box
- Code a list box’s SelectedValueChanged event
Adding a List Box to a Form
NOTE:The biggest change to the list box control is that you have to use the Items collection for most things.
You can use a list box control to display a list of choices from which the user can select zero choices, one choice, or more than one choice. The number of choices the user is allowed to select is controlled by the list box control’s SelectionMode property.
- Oneallows the user to select only one choice at a time in the list box. This is the default.
- None setting allows the user to scroll the list box, but not make any selections in it.
- MultiSimple-a mouse click or pressing the SPACEBAR selects or deselects an item in the list.
- MultiExtended-pressing SHIFT and clicking the mouse or pressing SHIFT and one of the arrow keys (UP ARROW, DOWN ARROW, LEFT ARROW, and RIGHT ARROW) extends the selection from the previously selected item to the current item. Pressing CTRL and clicking the mouse selects or deselects an item in the list.
The Windows standard for list boxes is to display a minimum of three selections and a maximum of eight selections at a time. If you have only two options to offer the user, you should use radio buttons instead of a list box.
Adding Items to a List Box
The items in a list box belong to a collection called the Items collection. The first item in the Items collection appears as the first item in the list box, the second item appears as the second item in the list box, and so on. A unique number called an index identifies each item in a collection. The first item in the Items collection—and, therefore, the first item in the list box—has an index of zero; the second item has an index of one, and so on.
You use the Items collection’s Add method to specify the items you want displayed in a list box control. The syntax of the Add method is object.Items.Add(item), where object is the name of the control to which you want the item added, and item is the text you want displayed in the control. You can use the Items collection’s Insert method to add an item at a desired position in the list box. The syntax of the Insert method is object.Items.Insert(position, item).
If the list box’s Sorted property is False, the item is added to the end of the list. However, if the Sorted property is set to True, the item is sorted along with the existing items, and then placed in its proper position in the list. Visual Basic .NET sorts the list box items in ascending ASCII order, which means that numbers are presented first, followed by lowercase letters, and then uppercase letters.
Whether you display the list box items in sorted order, or display them in the order in which they are added to the list box, depends on the application. If several list items are selected much more frequently than other items, you typically leave the list box’s Sorted property set to False, and then add the frequently used items first, so that the items display at the beginning of the list. However, if the list box items are selected fairly equally, you typically set the list box’s Sorted property to True, because it is easier to locate items when they appear in a sorted order.
The SelectedItem and SelectedIndex Properties
A list box’s SelectedItem property and its SelectedIndex property can be used both to determine the item selected in the list box and to select a list box item from code.
You can retrieve the text of the selected item as in:
strItem = Me.HourListBox.SelectedItem
or you can set an item using SelectItem and specifying the text you want
Me.HourListBox.SelectedItem = 40
Or SelectedIndex
Me.HourListBox.SelectedIndex = 4
If a list box allows the user to select only one item at a time, it is customary in Windows applications to have an item in the list box selected when the interface appears. The selected item, called the default list box item, should be either the most used selection or, if all of the selections are used fairly equally, the first selection in the list.
Walkthrough:
Update the Payroll Application
Open VBNET\Tut07\Payroll Solution
Complete the solution by
- Adding list box controls
- Coding the GetFwtTax function (make your students tax experts)
- Call GetFwtTax from the CalculatButton Click event
Quick Quiz
- What would you do to allow more than one item to be selected in a list box? ANSWER: Set SelectionMode to MultiSimple or MultiExtended.
- What is the order items are sorted in a list box and why? ANSWER: Numbers are sorted first, followed by lowercase letters, and then uppercase letters. This is the ASCII sequence.
- What is the Items collection? ANSWER: Each item added to a list box is added to the Items collection. You use this to access the list.
Completing the Payroll Application
Lesson C Objectives:
After completing this lesson, you will be able to:
- Add an existing form to a solution
- Add a new module to a solution
- Code the Sub Main procedure
- Create an instance of a form
- Display a form object using the ShowDialog method
Adding an Existing Form to a Solution