Visual Basic 2005 Guide
The Wages Program
You are going to write a program to calculate the pay of an employee. The user will be able to type in the hours worked and any overtime, select a rate of pay from a list and, after pressing a button, see how much pay is due.
Step 1 - Designing The Form
Your form will need to look like the screenshot below,
When designing the form, bear in mind the following,
- The rates of pay are stored in a list box. To add items to the list box at design time, select the items property and just type them in.
- To the left of the overtime text box, there is a check box with the text property set to, Overtime. The checked property is set to false.
- The overtime text box has its visibility property set to false. It will only be shown on screen if the check box is selected.
Step 2 - Making The Overtime Text Box (Dis)appear
Double click the check box to bring up the code window with the CheckChanged event handler. You need to write code so that if the checked property of the check box is true, the overtime text box has its visibility set to true. Otherwise the visibility of the text box should be set to false. Write the code, save your work and test the program.
Step 3 - Making Sure That A Pay Rate Is Selected
Our program will crash if the user doesn't select a rate of pay. We can test for this when they press the button or make one of the items selected when the program starts.
To select an item in the list, you change the list box's SelectedIndex property to the number of the item. The first item is numbered 0. You could do this in the form's load event handler.
If no item in the list is selected, the SelectedIndex property is equal to -1. If this is true when the button has been pressed, you can use the line Exit Sub to force the program to stop trying to calculate the pay.
Step 4 - Calculating The Pay
- Double click on the button to bring up its event handler. You will need to declare a series of variables to store the information that you are working with.
- Find out the basic rate of pay by setting a single variable to equal the list box's SelectedItem property.
- Find out the number of hours worked and multiply them by the rate of pay to work out the person's basic pay.
- If overtime has been entered, multiply the amount of overtime by double the rate of pay. Add this on to the basic pay to get the total payable.
- You can use the format command to make sure that the result is formatted for currency. For example, strPay = Format(sglTotalpay, "£#0.00")
Save your work and test your program.