Section VB: Visual Basic Programming

Section VB: Visual Basic Programming Students who are thinking of becoming programmers enroll in two- or three-credit hour courses to learn various pr...
Author: Ginger Lynch
10 downloads 1 Views 327KB Size
Section VB: Visual Basic Programming Students who are thinking of becoming programmers enroll in two- or three-credit hour courses to learn various programming languages. This series of labs is meant to introduce you to programming and help you decide whether you would like to further pursue this topic in the future. These labs will show you how to start Visual Basic, design and code some programs and run them. You will learn about a few “basic” program statements and be given step-by-step instructions on how to design some forms (which become windows) and code some simple programs. The section ends by asking you to provide some assessment feedback to your instructor.

Lab Assignments: VB-1.

Design and Code a Program to Count Fish

This first lab gives you step-by-step instructions on how to design a VB program and code it. You then test the program and make modifications to it.

VB-2.

Design and Code a Program to Calculate a Price including Sales Tax

This second lab asks you to rely on the skills you learned earlier. You will be led through the development of a program that accepts a quantity of diskettes that were purchased and calculate the amount due including sales tax.

VB-3.

Design and Code a Program to display a Countdown and Explode a Firecracker

This third lab asks you to rely on the skills you learned earlier. Step-by-step instructions are given only for new topics. You learn a little about program “loops.”

VB-4.

Design and Code a Program with some “Glitz”

This fourth lab again asks you to rely on previous work; however, step-by-step instructions are still provided for new material.

VB-5.

Assessment Exercise: Instructor Feedback

Many instructors will assign this last lab of this section. In it you will create a memo to inform your instructor about your reaction to these programming labs.

Last revised: 24-Aug-09 by djr

Folder: 133VB Input:

The program code

Output:

A set of four files is created for each program you write; these have the same name and have extensions: .VBW .VBP .FRM .FRX Labs VB-1, VB-2, VB-3, and VB-4 each produce a set of files with names: FISHPOND PRICING COUNTDOWN GLITZ

Note: Your instructor may assign additional programs or choose to not assign all the ones included here. Also your instructor may want to visually check the programs before you submit the printouts

Last revised: 24-Aug-09 by djr

-- -- -- -- -- -- H A N D – I N ASSESSMENT.

SHEET

-- -- -- -- -- --

SECTION VB: VISUAL BASIC

Name:

________________________________________________

Date:

__________________________

Lab

Description / Check List

VB-1

First Project: FISHPOND

Possible Points Earned Points ________

________

________

________

________

________

________

________

Title on Form 3 Identifying Labels 2 Labels for Data Entry Calculate CommandButton Works Correct Result Displayed in Label Flag Displayed on Button Click Binoculars Image Name Displayed on Image Click Printouts Submitted Execution Visually Checked by Instructor

VB-2

Second Project: PRICING Title on Form 1 TextBox for Data Entry 4 Labels to display results 5 Identifying Labels Calculate CommandButton Works Correct Results Displayed in Labels Clear CommandButton Works Quit CommandButton Works Printouts Submitted Execution Visually Checked by Instructor

VB-3

Third Project: Countdown Title on Form Image of Firecracker with Tool Tip Identifying Label For/Next Loop correct Firecracker Explodes Correctly Printouts Submitted Execution Visually Checked by Instructor

VB-4

Fourth Project: GLITZ Title on Form Image on Form Identifying Label Circles Drawn Correctly Printout Submitted Execution Visually Checked by Instructor Last revised: 24-Aug-09 by djr

TOTAL

TOTAL POINTS FOR ALL ASSIGNED LABS

________

________

Visual Basic Programming 1. Review the CST133 Web Page checking for changes/corrections to this VBSection of the Lab Packet — the instructions for accessing the web page are found in Appendix F. 2. Review Computer Programming in your text book: Chapter 10. 3. Read pages 4-6 of this VB-section of the Lab Packet. 4. Review the rest of this VB-section to get an idea of the scope of these assignments. I.

Introduction to Visual BASIC. A.

Visual Basic is a programming language. You can write a program in this language and the Visual Basic Program can translate your statements, one after another, into the 0's and 1's the computer needs in order to process. That is, your Visual Basic source program is transformed into an object program in machine language that can be executed (run). With Visual Basic you can create programs that run in Windows — they will have title bars, menus, and other useful objects involved with a Graphical User Interface (GUI). The programs that you create will "look" like the other Windows programs you have been running, such as WordPad, Notepad, and the Calculator. Remember, Windows has a Common User Interface — a set of rules that all programs must follow. Visual Basic allows us to create programs that follow the conventions in this Common User Interface.

B.

The current version of Visual Basic at Delta College is .NET 2008 — however, for CST133 we will use the older, less-complicated Version 6.0 . Delta lab systems in some KWing rooms, LLIC Open Lab, Ricker Center, DCMC, and DCPL have Visual Basic Version 6.0 Professional installed. It is important to note that Visual Basic is upward compatible but not downward compatible. This means that you can code a program in an older version (such as 5.0 or 4.0) and run it in the 6.0 version — you are going upward — but you can't do the reverse. You cannot code a program in the 6.0 version and run it on an older version — you cannot go backward. Other Delta labs may have a lower version installed — some features shown here may not be available in these lower versions.

C.

Visual Basic uses graphic objects — you create these objects using the controls in the Tool Box on the left of the Visual Basic Screen.

Last revised: 24-Aug-09 by djr

NOTE: Most students do NOT have Visual Basic installed on their home computers. Therefore, plan to do this lab on campus.

D.

Visual Basic allows you to design a Form — this form will become the window containing your application when you run it. During the design phase, you as the programmer create various objects (TextBox, Label, CommandButton, Image, etc.) and move them around on your form. Normally, the default has been set to show a grid of dots on the form to help you line objects up — this grid does not appear when you run your application. You create an object by double-clicking its Control on the Tool Box on the left side of the Visual Basic window. The object will appear within your form — simply point at it, hold the mouse button down and drag it to its new location and drop it by letting up on the mouse button. When you click on an object, handles appear — small boxes at each corner and the mid-point of each side. If you point at one of these handles and hold the mouse button down, the object changes size as you drag your mouse.

E.

Each object has properties — a TextBox, a Label, a CommandButton, an Image, and the Form itself have properties. Properties allow the programmer to assign names to objects so they can be referred to in program instructions. You as the programmer can set properties such as background color, size and color of font, captions (text within the Last revised: 24-Aug-09 by djr

object), whether the object is visible or not, and many other very handy things. When you select an object by clicking on it, you will see a Properties Window over to the right — you can scroll through these properties and change them as necessary. You do need to be careful that you are working with the correct object, however. Of course, you see the object has handles and is thus selected. Also, the name and type of the object is shown at the top of its properties window. For example, the Label in the above exhibit is called "Label1" so this is listed at the top of its properties window: Label1 Label F.

You may have heard about Object Oriented Programming (OOP). With OOP, objects have code associated with them. For example, consider how you bold some text in Word. You select the text and click on the "Bold" button. The necessary Program instructions to bold the selected text is connected (Oriented) to the "Bold" button Object. You will associate program code with some objects. When you double-click an object a "Code" window pops up. So, you click an object to select it — and you doubleclick an object to get to code associated with that object. If you mean to select but double-click by mistake, simply close the code window.

G.

Often it is easiest to develop a program in stages. Design part of it — test the program by running it — add some additional design — re-test it. You can start the program several ways. You can click on Run and click on Start. You can press the [F5] key. And you can use a "Start" button provided by VB. When you run the program it executes in its own window, complete with Maximize, Minimize, and Close buttons. You can end the program by clicking on its window's close button [X]. You can attach code to end the program to an object such as a CommandButton. You can also use an "End" button provided by VB. The "Start" and "End" buttons resemble those on a VCR or DVD player.

Lab VB-1: Develop and Run Your First Visual Basic Program • • • •

I.

Design a Form with TextBox, Label, CommandButton, Image Change some Properties of Objects Code some Program Instructions Test a Windows Application

Introduction. A.

Accessing Visual Basic. 1. Insert your USB Drive. 2. In WINDOWS, click on: Start All Programs Applications Last revised: 24-Aug-09 by djr

Microsoft Visual Basic 6.0 Microsoft Visual Basic 6.0 3. "Standard EXE" in the New Tab should be selected. Click on the [Open] Button. B.

Developing an Application Program. 1. You will develop an application program in a project that contains one form. By default the project is named "Project1" and the form is named "Form1" You will place various objects on this form. This project concerns entering two pieces of data — the number of fish in each of two ponds. The program will add the two numbers together and display their sum, the total number of fish. Each piece of data will be entered into a TextBox — Labels will give instructions for data entry and display the result. Eventually you will create a CommandButton that can be clicked to run program instructions to produce the answer and display it. You will also place some graphics on the form. The final form will look similar to this:

Last revised: 24-Aug-09 by djr

PART A:

PART B:

As the program begins to run two Textboxes are available for data entry. A Label is above each giving instructions to "Input number of fish in pond 1" and pond 2 Below the two empty Textboxes a Label says "Total Fish:" Over to the right is a CommandButton that says "Click to Calc." In the bottom left corner a graphic of some binoculars is shown. The title bar includes the programmer's name.

Here is the result of the program. The user has entered a "3" in the first Textbox, tabbed to the second Textbox and entered a "4." The button "Click to Calc" has been clicked and the result "7" is to the right of the Label "Total Fish:" A flag in the shape of the USA has also been displayed as a result of the CommandButton. Finally, the binoculars has been clicked and the name of the programmer is shown.

C.

D.

Assigning Properties to the Form. 1. Click anywhere within the form to make sure it is selected — it has the focus. The Properties Window should be visible over to the right. If it is not visible, press [F4]. If it is partially obscured, click in the blue area of its title and drag it into place. You should see the name of the form at the top of the Properties Window: Properties Form1. 2. Two columns make up the Properties Window — a list of Properties on the left and their settings on the right. Click on the Property "Caption" — scroll within the Properties Window if necessary. The pre-set Caption is "Form1" — it appears in the Title Bar of the form. 3. Change the Caption by keying: Fishpond programmed by your name 4. Notice that the Caption on the form's Title Bar has changed. If your name was too long for the title bar, just key your last name. 5. Let's change the color of the form. Its color is called the "BackColor" so find that property and this time double-click it. A window drops down that has two tabs — click on the "Palette" tab and observe a selection of colors that are available. Choose a light color by clicking on it. 6. Notice that the color of your form has changed. Using the TextBox Control — [ab|]. 1. In the Tool Box at the left, double-click on the TextBox Control. 2. A TextBox named "Text1" appears in the center of the form. Drag it into position as shown in the example on the previous page. 3. Double-click on the TextBox Control. 4. A second TextBox named "Text2" appears in the center of the form. Drag it into position to the right of the first TextBox. 5. Click on the first TextBox, Text1, to select it — to set the focus on it — it should now have handles. 6. The Properties Window should now have: "Properties - Text1" at the top. 7. We want to be able to refer to this in a meaningful way in our program. Let's rename it. Since it will eventually contain the data for the number of fish in pond #1 we will Last revised: 24-Aug-09 by djr

name it Pond1Textbox — with no spaces. The "Name" Property is at the very top of the list, click on it and key Pond1Textbox 8. This is important! Notice that the text in the TextBox on the form did NOT change since it does not contain the "Name." The Property for this text is called "Text" so scroll down the list of properties and click on it. We do not want any text to be in the way so press the Delete key once. 9. Notice that the first TextBox on the form is now empty. 10. Click on the second TextBox, Text2, and do steps 6 through 9 for it — but of course you will name it Pond2Textbox E.

F.

Using the Label Control — [ A ]. 1. In the Tool Box at the left, double-click on the Label Control. 2. A Label named "Label1" appears in the center of the form. Drag it into position as shown in the example on the previous page — it's above the first TextBox. 3. Create a second Label that will automatically be called "Label2." 4. Drag Label2 above the second TextBox. 5. Create two more Labels — they will be called "Label3" and "Label4." 6. Drag Label3 below the first TextBox and Label4 below the second TextBox. 7. An example of your form is shown on the next page . . . 8. Click on Label1 to select it. 9. Double-click its BackColor Property, click on the Palette tab and select the same color you used for the form. 10. Scroll down and click its Caption Property. Key the following: Input number of fish in pond 1: 11. Notice that the caption of the label changed on the form. 12. Click on Label2 to select it. 13. Do steps 9 through 11 for Label2 but use the Caption: Input number of fish in pond 2: 14. Click on Label3 to select it. 15. Do steps 9 through 11 for Label3 but use the Caption: Total Fish: 16. Do steps 9 through 11 for Label4 but when you change its Caption, get a blank label by pressing the Delete key. 17. With Label4 still selected, change its name to DisplayTotalFishLabel Using the CommandButton Control. 1. So far you have two TextBoxes and four Labels on your form — but they are just sitting there — nothing will happen to them when you run your program because we have not coded any instructions. It is always a good idea to put yourself in the place of the user of your program. If we were to run this program, what would happen? The user would see the labels giving instructions to "Input number of fish in pond1:" and could key in that data. Seeing the second instruction on the form, to "Input number of fish in pond2:" the user could tab to the next data entry location or click in Last revised: 24-Aug-09 by djr

2. 3. 4. 5. 6. 7.

it and key in that data. Now the user needs a mechanism to continue to process this data and get a result. We will use a CommandButton for this. Double-click the CommandButton Control in the Tool Box. The button automatically has the Caption "Command1." Drag Command1 to the right of DisplayTotalFishLabel as shown in the exhibit in Part B. With Command1 still selected, change its Caption Property to: Click to Calc Notice that the caption of the CommandButton has changed on the form. Change its Name Property (at the top of the list) to: CalculateButton We need to code some instructions that will be executed when CalculateButton is clicked. Double-click the Click to Calc Button on the form to open its code window. The first and last lines are already coded for you: Private Sub CalculateButton_Click()

End Sub 8. Click the mouse to position between those lines and press the [Tab] key and then key the following program code. Make sure there is a single apostrophe ( ' ) before Declare, Assign, Add and Display. Those are comments and are ignored by VB. NOTE: Coding examples are shown throughout this lab. You need to distinguish between some important characters:

1 l

is the number one is the lower case letter L

Here is the code to key: 'Declare variables Dim Pond1 As Integer Dim Pond2 As Integer Dim TotalFish As Integer 'Assign input from text boxes to variables Pond1 = Val(Pond1Textbox.Text) Pond2 = Val(Pond2Textbox.Text) 'Add variables to determine total number of fish TotalFish = Pond1 + Pond2 'Display the results DisplayTotalFishLabel.Caption = TotalFish 9.

Thus, your coding looks like this: Private Sub CalculateButton_Click() 'Declare variables Dim Pond1 As Integer Last revised: 24-Aug-09 by djr

Dim Pond2 As Integer Dim TotalFish As Integer 'Assign input from text boxes to variables Pond1 = Val(Pond1Textbox.Text) Pond2 = Val(Pond2Textbox.Text) 'Add variables to determine total number of fish TotalFish = Pond1 + Pond2 'Display the results DisplayTotalFishLabel.Caption = TotalFish End Sub 10.

Look at your code once more — check to make sure you entered it exactly as shown above, What this is saying is this: Create three variables named Pond1, Pond2, and TotalFish and make them integers (so they can hold whole numbers without fractions):

Dim Pond1 As Integer Dim Pond2 As Integer Dim TotalFish As Integer When you Click on the Click to Calc Button, take what the user typed in the text boxes, convert it to values and store in the two variables Pond1 and Pond2:

Pond1 = Val(Pond1Textbox.Text) Pond2 = Val(Pond2Textbox.Text) Add the variables together to get the total number of fish which is stored in the variable TotalFish:

TotalFish = Pond1 + Pond2 Display the results of the calculation (stored in the TotalFish variable) in the caption of the label DisplayTotalFishLabel:

DisplayTotalFishLabel.Caption = TotalFish 11. Close the code window by clicking its [X]. G.

Test your Program. 1. Before testing your program, you should save it in 133VB on your USB Drive. Actually, you have two files that will be saved, one for the "project" and one for the "form" — you'll name them both "fishpond" but they will end up with different extensions. 2. Click on File and click on Save Project. When prompted for the two names, key FISHPOND making sure you are in the folder 133VB. Last revised: 24-Aug-09 by djr

3. Test your program by running it — either click the [Start] button, press [F5] or use the menu Run / Start 4. Your application starts running in a window. Notice that it has an entry on the Taskbar — just like other programs! 5. In the first TextBox, key 3 then tab to the second TextBox and key 4 then click on the CommandButton that says "Click to Calc." Your result should appear in the window. 6. Close your program by clicking on its [X]. H.

I.

Use the Image Control to Add Binoculars to your Form. 1. Double-click the Image Control. 2. The resulting Image object has a dotted line as its border — its default name is Image1 — it is probably right on top of the Label you use for your result. Being careful to point at the dotted border, drag Image1 below the Label that says "Total Fish:" — as shown in the exhibit in part B. Note that if you point within the Image you will drag the Label instead! Change the Name property to BinocularsImage. 3. With Image1 selected, scroll down its properties until you reach the "Picture" Property. Double-click on the "Picture" Property to get a "Load Picture" window. 4. You will use a picture called an "icon" — its name is binoculr.ico — and it is in a folder called: C:\Program Files\Microsoft Visual Studio\Common\Graphics\Icons\Misc 5. To get to the correct folder, click the down-arrow next to the "Look in:" box and position yourself at the C:\ — then double-click on Program Files — Microsoft ... until you are in the Misc folder and see the BINOCULR.ICO file. 6. Click on the BINOCULR.ICO file to select it and click the [Open] button. 7. You should now see the binoculars on your form. Add a Label that Can Display the Programmer ID — Your Name. 1. Double-click Label Control; drag the resulting Label to the right of the binoculars image. 2. This new label will be used to display the programmer id — your name. With this new Label selected, change its Name Property to ProgrammerNameLabel 3. Change its Caption to a blank — Double-click the value and press the [Delete] Key. 4. Make its BackColor the same as that of the form. 5. We need some code — double-click BinocularsImage (the binoculars). 6. Again, the first and last lines of the necessary code have been generated for you: Private Sub BinocularsImage_Click() End Sub You can see that this is a Subroutine to be run when BinocularsImage is Clicked. 7. We need to do two things — add a Caption and make it visible. Instead of presetting the properties for Image1, we will set them with program instructions. Add the following two lines of code (tabbing them in as you did before): ProgrammerNameLabel.Visible = True ProgrammerNameLabel.Caption = "Programmed by your name" Last revised: 24-Aug-09 by djr

The first statement that will be executed when BinocularsImage is clicked will set the visible property of ProgrammerNameLabel to "True" — that is, it will be visible. The second statement changes the Caption property of ProgrammerNameLabel to "Programming by you." 8. We want to be able to remove the display of "Programming by you." Note that above the coding area are two rectangular text boxes. The left one shows that the object we are working with is BinocularsImage. The right one shows that we are working with the code that will be executed when we Click on BinocularsImage. Move your mouse and click on this right-most entry. Move your mouse pointer down and click on DblClick. A new subroutine is generated for you as shown here. 9. When Image1 is double-clicked, we want to remove the display of the Programmer id — that is, not make it visible. To do this code the following instruction (shown bold here): Private Sub BinocularsImage_DblClick() ProgrammerNameLabel.Visible = False 'Hide programmer name End Sub NOTE: Note that the instruction is followed by a single quote that starts a comment — comments such as this are important in documenting a program. 10. Close the code window — [X]. J.

Re-Test your Program with its new capability. 1. Save your project — just in case. 2. Test your program by running it. 3. Key 3 and key 4 and click "Click to Calc." Your result should appear. 4. So far, the results are the same as before. Let's test the new capability. 5. Click the binoculars — your name should appear. 6. Double-click the binoculars — your name should disappear. 7. Close your program.

K.

One more "Glitsy" Thing — Another Graphic. 1. Let's place a flag on the form and make it visible when the "Click to Calc" button is clicked. 2. Double-click another Image and drag it into place below the "Click to Calc" button. (Remember to drag by its dotted-line border), 3. Change its Name property to FlagImage 4. Change its Visible property to False — make sure that you are working with FlagImage and not the form (otherwise the form would become invisible!). 5. Some people become confused when they do this step — you set the Visible Property of FlagImage to False and it's still visible on the form. That's because it is visible as you design your form and program — it will not be visible when you run the program. 6. Double-click the Picture Property of FlagImage. Last revised: 24-Aug-09 by djr

7. As you did before in the resulting "Load Picture" window, position in the correct folder. You will probably be in the Misc folder from your last image retrieval, so click the "Up One Level" icon. You will be in the icons folder — click on the Flags folder and click on Open. Select a flag such as CTRUSA.ICO and click on Open to place the flag on your form. L.

Change the "Click to Calc" Code. 1. Double-click the "Click to Calc" button to bring up its code window. 2. Add a line of code (the new line is shown here in bold): 'Display the results DisplayTotalFishLabel.Caption = TotalFish FlagImage.Visible = True 'make flag appear End Sub 3. Close the code window.

M.

Final Test your Program with its new glitsy capability. 1. Save your project — just in case. 2. Test your program by running it. 3. Key 3 and key 4 and click "Click to Calc." Your result should appear. 4. Note that this time the flag also appears! 5. Click the binoculars — Double-click them - Click them once again. The appearance of your name should still work as before. 6. Close your application window. Congratulations!

N.

Verification by Instructor. 1. An Assessment Hand-In Sheet is at the beginning of this VB-section of the Lab Packet. Your instructor may choose to view the running of your program during lab — and/or have you print some of it out. The Assessment Sheet has a place for either/both methods of assigning points to your work. Distance Learning students will have to submit the program and form that was developed — instructions will be provided.

O.

Printing your Assignment. 1. If you are required to print your work, click on File and click on Print. 2. In the Range area at the left of the Print Window, Current Module should already be checked. 3. On the right, the Print What area should have Code checked. Also click on Form Image to select it. 4. Click on OK to print both the form and the code. 5. Write your name and "Lab VB-1" on both pages and place in your folder with your Assessment Hand-In Sheet. Last revised: 24-Aug-09 by djr

• • •

Place the Assessment Hand-In Sheet in your folder (with Instructor's Verification if your program was viewed). Place printouts of your program's form image and code in your folder (if requested by instructor). Label printouts as Lab VB-1 with Your Name (if printouts requested by instructor).

• •

Printouts must have your name clearly in view and be labeled as Lab VB-1. Labs must be placed in sequence in your folder.



Include the Assessment Hand-In Sheet that is at the beginning of this section.

LAB VB-2 — Practice With A Simple Price Program •

Reinforce knowledge of Visual Basic Program design and testing.

I. Program Requirements. A.

You will be given step-by-step instructions — but review the previous lab for steps that are similar to what you have already accomplished.

B.

Pretend you are a programmer for the Deltoid Diskette Company. Your company is about to place kiosks in malls and at industry shows in Michigan — where they will sell boxes of diskettes for a price of $3.99 each. Deltoid needs a program that will accept the quantity purchased and calculate the extended price (quantity purchased times price), calculate the sales tax based on 6% (extended price times 6%), and then calculate the amount due (extended price plus sales tax). Here's an example of the calculations: 5 Quantity Purchased $ 3.99 Price for Each Box $19.95 Extended Price (5 times $3.99) $ 1.20 Sales Tax ($19.95 times 6% rounded) $21.15 Amount Due ($19.95 plus $1.20)

C.

We need places in memory to store this data — these places are called "variables" in our program — there's five pieces of data we need to keep track of. Thus, we will store the Quantity Purchased in a variable called Quantity. The other four variables will hold currency values — Price, ExtendedPrice, SalesTax, and AmountDue. Notice that there are no spaces within the variable names. Last revised: 24-Aug-09 by djr

D.

Thinking ahead to the layout of the window where our program will execute, we need a place to enter the Quantity Purchased — it will be a text box named QuantityTextbox. We also need places to display the values we are using and calculating — these will be in labels, such as: PriceLabel, ExtendedPriceLabel, SalesTaxLabel, and AmountDueLabel. We also want five labels to use for describing the various places in our window — we will use labels that just have their default names (since we won't need to change them or use them in any way other than displaying on the screen). Finally, thinking about the person using our program (the end user), that person needs to be able to calculate the values once the Quantity Purchased has been entered in. Also, he/she needs to be able to clear the previous values out and start fresh. Finally, he/she needs to be able to quit the program. We will use three CommandButtons for these purposes — CalculateButton, ClearButton, and QuitButton. An image of the completed window is shown at the top of the next page — below it is an image of the form as we are developing it — with its default captions.

II.

Start a New Project. A. If you have closed Visual Basic, start VB with a new project as you did in Lab VB-1. If Visual Basic is still running, click on File and click on New Project. Click on Standard EXE and click on OK.

III.

Design of Form. A. Change the following Property of your Form (as shown, substituting your name for Annie Student's): 1. Click anywhere within the form to select it. 2. Caption Property on the right: Deltoid Diskettes -- Annie Student 3. Height Property: 4500 B. Place an Text Box in the upper left corner of your Form. 1. Double-click the Text Box tool. 2. Drag to position the resulting Text Box as shown. 3. Name Property: QuantityTextbox 4. Text Property: Blank (delete existing text) 5. Alignment Property: Last revised: 24-Aug-09 by djr

1- Right Justify C. Place a Label below the text box. 1. Double-click click the Label tool. 2. Drag to position the re resulting Label as shown. 3. Name Property: PriceLabel 4. Caption Property: [Delete] — — for a blank Label 5. Alignment Property: 1- Right Justify D. Place three more Labels below as shown — Their Caption property should be blank and their Alignment property should be 1 - Right Justify (like the label you just created). Their Name property should be as follows: • Label1: ExtendedPriceLabel • Label2: SalesTaxLabel • Label3: AmountDueLabel E. Click on the text box — hold the [Ctrl] Key down and click on the four labels below it. With all five objects selected, click on the Format menu, click on Align and click on Lefts. F. Place and line up five Labels in a column to the right as shown — the ones captioned Label5 through Label9 in the example (they will now have the default captions Label1 thru Label5). Their Caption property should be as follows: • Label1: Enter Quantity Click Calculate (it will automatically wrap to a 2nd line) • Label2: Price • Label3: Extended Price • Label4: Sales Tax • Label5: Amount Due G.

Place a CommandButton over to the right as shown — its Caption is Command1 in the example — Change its Caption property to be Calculate and change its Name property to CalcButton

H.

Place two more CommandButtons below the first one as shown — their Captions are Command2 and Command3 in the example. For Command2,, change its Caption property to be Clear and its Name property to be ClearButton.. For Command3, change its Caption property to be Quit and its Name property to be QuitButton.

IV. A.

Writing the Program C Code. Write the code to Quit via the Quit CommandButton — when it is clicked: 1. Double-click the Quit CommandButton to open the code window. 2. A code template is created for you — shown in smaller font below. Last revised: 24-Aug-09 by djr

3. Enter the following code (the code that is bold and larger): Private Sub QuitButton_Click()

End End Sub

4. Double-check your keying and close the code window. B.

Write the code to create our variables, initialize the price, and cause the price to be displayed in a currency format in the appropriate label. NOTE: Each variable is created with the Dim (Dimension) statement as a certain kind of variable — we will use two kinds. Integers are whole numbers (no fraction or decimal part) and Currency holds currency values. We will place this code in the portion that occurs when our form is loaded at initialization time. 1. Double-click the Form to open the code window. 2. A code template is created for you — shown in smaller font below. As you key your code, remember that Visual Basic is fussy! Key exactly as shown — be especially careful to avoid putting spaces where they do not belong. 3. Enter the following code (the code that is bold and larger): Private Sub Form_Load( )

Dim Quantity As Integer Dim Price As Currency Dim ExtendedPrice As Currency Dim SalesTax As Currency Dim AmountDue As Currency Price = 3.99 PriceLabel.Caption = FormatCurrency(Price) End Sub

4. Double-check your keying and close the code window. C.

Write the code for the Clear CommandButton that will re-set the text box and three of the labels (note that when you see "" it means to key two double-quotation marks sideby-side without a space in between) — the last instruction sets the focus in the text box at the top — that's where the cursor will be: 1. Double-click the Clear CommandButton to open the code window. 2. A code template is created for you — shown in smaller font below. 3. Enter the following code (the code that is bold and larger): Private Sub ClearButton_Click()

QuantityTextbox.Text = "" ExtendedPriceLabel.Caption = "" SalesTaxLabel.Caption = "" AmountDueLabel.Caption = "" QuantityTextbox.SetFocus End Sub

4. Double-check your keying and close the code window. Last revised: 24-Aug-09 by djr

D.

Write the code for the Calculate CommandButton that will calculate the values and place them formatted correctly in the correct labels — Note that we need to work with the value of the text in QuantityTextbox and that's why the second instruction looks as it does: 1. Double-click the Calculate CommandButton to open the code window. 2. A code template is created for you — shown in smaller font below. 3. Enter the following code (the code that is bold): Private Sub CalculateButton_Click()

Price = 3.99 ExtendedPrice = Price * Val(QuantityTextbox.Text) SalesTax = ExtendedPrice * 0.06 AmountDue = ExtendedPrice + SalesTax ExtendedPriceLabel.Caption = FormatCurrency(ExtendedPrice) SalesTaxLabel.Caption = FormatCurrency(SalesTax) AmountDueLabel.Caption = FormatCurrency(AmountDue) End Sub

4. Double-check your keying and close the code window.

V.

Run and Test Your Program

A.

Save your project and form in 133VB — — use the name PRICING for both the form and the project.

B.

Run your program. 1. Key the Quantity: 5 2. Click the Calculate CommandButton. 3. Did you get the correct results? That is, do your results match the example you saw? • If so, continue on. • If not, fix your code and re-try. 4. Click the Clear CommandButton. 5. Did you get the correct results? Were the appropriate objects on the form cleared? • If so, continue on. • If not, fix your code and re-try. 6. Key the Quantity: 4 7. Click the Calculate CommandButton to get new results. 8. Prove these results by hand-calculating. 9. Click the Quit CommandButton to end your program.

C.

Verify your work. 1. Your instructor will announce whether you are to show the results of your execution on the screen or submit your program and form for grading.

D.

Print 1. Print the form and code for submission. Follow the instructions on the previous lab. Last revised: 24-Aug-09 by djr

• • •

Place the Assessment Hand-In Sheet in your folder (with Instructor's Verification if your program was viewed). Place printouts of your program's form image and code in your . Label printouts as Lab VB-2 with Your Name.

• •

Printouts must have your name clearly in view and be labeled as Lab VB-1. Labs must be placed in sequence in your folder.



Include the Assessment Hand-In Sheet that is at the beginning of this section.

LAB VB-3 — Countdown Program • • •

I.

Reinforce knowledge of Visual Basic Program design and testing. Develop a program with fewer step-by-step instructions. Learn about loops.

Program Requirements. A.

You will be given step-by-step instructions for any new material — review the previous lab for steps that are similar to what you have already accomplished.

B.

This program will have three Labels, two Images and two Command Buttons. One Label will be used for a description, another will be used to display a sequence of numbers and the last one will display the programmer's name. One Command Button will be used to start number sequence and the other will be used to end the program. When the user clicks the Start button, code will execute displaying an unexploded firecracker and a sequence of numbers counting down from 10 to 0. When the numbers reach zero, the firecracker will "explode!"

C.

To display the numbers, we will use a For/Next loop. A loop is a series of instructions that are executed multiple times, like displaying a sequence of numbers. Our loop displays the highest number (10 in this case) then repeats and displays the next highest number (9) and so on, until it reaches zero and stops.

D.

Computers are fast! Normally, a computer can count down from 10 to 0 and display the numbers so fast that to us it would seem to be instantaneous. Therefore, we need to slow the computer down. And to do that, we will use another For/Next loop.

II.

Start a New Project.

Last revised: 24-Aug-09 by djr

A.

III.

If you have closed Visual Basic, start VB with a new project as you did in Lab VB-1. If Visual Basic is still running, click on File and click on New Project. Click on Standard EXE and click on OK.

Design of Form.

A.

Change the following Property of your Form: 1. Caption Property: Countdown Lab programmed by [your name]

B.

Place a Command Button near the bottom of the form. 1. Name Property: StartButton 2. Caption Property: Start Countdown

C.

Place another Command Button below the Start Countdown button. 1. Name Property: QuitButton 2. Caption Property: Quit

D.

Place an Image in the middle of your form. 1. Name Property: Firecracker1Image (that's the number 1 at the end of the name) 2. Picture Property: Use the icon named MISC39A.ICO in the Misc folder. 3. ToolTipText Property: Unexploded firecracker Note that a Tool Tip is a small window that pops up when your mouse pointer is over the object. Thus, when this program runs and the user moves the mouse pointer over the image of the firecracker, "Unexploded firecracker" will pop up briefly.

E.

Place an image of an exploded firecracker directly on top of the unexploded firecracker image. 1. Name Property: Firecracker2Image 2. Picture Property: Use the icon named MISC39B.ICO in the Misc folder. 3. ToolTipText Property: Exploded firecracker 4. Visible Property: False

F.

Place a Label in the upper left middle of the form. Be sure to widen it a little bit.. 1. Name Property: DisplayCountdownLabel 2. Caption Property: Countdown 3. Font Property: Size 14

G.

Place a Label in the upper right middle of the form. 1. Name Property: DisplayNumbersLabel 2. Caption Property: [none] 3. Font Property: Size 14

IV. A.

Writing the Program Code. Code for the Quit Command Button. 1. Double-click the Quit Command Button to open the code window. 2. Under Private Sub QuitButton_Click(), key the following code: Last revised: 24-Aug-09 by djr

'quit the program End B.

General Comments: 1. The code windows has two dropdown lists at the top. Click on the left one to see a list of objects. Click on (General). 2. Key the following: ' ** A Countdown For/Next Loop ** ' ** Programmed by [your name] ** ' ** Date: [today's date] **

C.

Code for the Start Countdown button: 1. Click on the left dropdown list again. This time click StartButton. 2. You are about to enter more involved code — remember that Visual Basic is fussy about syntax so you need to be fussy about keying the instructions correctly. Proofread your code after you have entered it in. 3. The tabs that are shown are not absolutely necessary for the program to run properly; however, good programmers use tabs to line logical statements up — it is much easier to understand and maintain a program that is entered with care. 4. Key the following code under Private Sub StartButton_Click() — it will execute when the Start Countdown button is clicked: 'declare variables Dim Countdown As Integer Dim Slowdown As Long 'show unexploded firecracker and hide exploded one Firecracker1Image.Visible = True Firecracker2Image.Visible = False 'start the countdown For Countdown = 10 To 0 Step -1 DisplayNumbersLabel.Caption = Countdown For Slowdown = 1 To 10000000 Next Slowdown DisplayNumbersLabel.Refresh Next Countdown 'show the exploded firecracker and hide unexploded one Firecracker1Image.Visible = False Firecracker2Image.Visible = True

V. A.

Save, Run and Test Your Program Click the Save button. Use COUNTDOWN for both the project and the form in 133VB. Last revised: 24-Aug-09 by djr

B.

Run your program. 1. Move your mouse pointer over the image of the firecracker to see the Tool Tip pop up. 2. Click the Start Countdown button. You should see 10, 9, 8, and so on through 0 appear. Then the firecracker should "explode." 3. Click the Quit button to end the program.

C.

Verify your work. 1. Your instructor will announce whether you are to show the results of your execution on the screen and/or print the form and code for submission. If printing is required, follow the instructions on the previous lab. Distance Learning students will follow special instructions. • • •

Place the Assessment Hand-In Sheet in your folder (with Instructor's Verification if your program was viewed). Place printouts of your program's form image and code in your folder (if requested by your instructor). Label printouts as Lab VB-3 with Your Name (if printouts requested).

• • •

Printouts must have your name clearly in view and be labeled as Lab VB-3. Labs must be placed in sequence in your folder. Include the Assessment Hand-In Sheet that is at the beginning of this section.

LAB VB-4 — A Glitzy Program • •

I.

Reinforce knowledge of Visual Basic Program design and testing. Develop a program with fewer step-by-step instructions.

Program Requirements. A.

II. A.

III.

This program needs an Image, a Label, and a Quit CommandButton. When the user Double-Clicks on the Image, some "Glitz" will occur — you'll see the results soon!

Start a New Project. If you have closed Visual Basic, start VB with a new project as you did in Lab VB-1. If Visual Basic is still running, click on File and click on New Project. Click on Standard EXE and click on OK.

Design of Form.

A.

Change the following Property of your Form: 1. Caption Property: Glitz Lab programmed by your name 2. Name Property: GlitzForm

B.

Place an Image of your choice in the upper left corner of the Form — with these Properties: Last revised: 24-Aug-09 by djr

1. Name Property: GlitzImage 2. Picture Property: pick something 3. ToolTipText Property: DblClick to see Glitz C.

Place a Label next to your Image — with these Properties: 1. Name Property: GlitzLabel 2. Caption Property: Go - Go - Run those Circles . . .

D.

Place a CommandButton in the bottom left corner of the Form — with the same Properties you used in the previous lab to allow the user to Quit.

IV.

Writing the Program Code.

A.

Code the Quit button the same way you did in the previous lab.

B.

Double-Click GlitzImage to open a code window and select the action DblClick 1. Key in the following code that will be executed when the image is Double-Clicked: Private Sub GlitzImage_DblClick() ' declare variables Dim Radius As Integer Dim Slowdown As Long Dim HorizontalValue As Long Dim VerticalValue As Long 'change label color to green GlitzLabel.BackColor = vbGreen 'change form color to green GlitzForm.BackColor = vbGreen 'assign width and height values to the variables VerticalValue = ScaleWidth HorizontalValue = ScaleHeight 'loop to draw the circles For Radius = 0 To VerticalValue Step 300 For Slowdown = 1 To 1000000 Next Slowdown Circle(Radius, HorizontalValue / 2), Radius / 3 Next Radius End Sub 2. Close the code window.

V. A.

Run and Test Your Program. Save your project and form in 133VB on your USB Drive — use the name GLITZ Last revised: 24-Aug-09 by djr

B.

Run your program. 1. Move your mouse pointer over your Image to see the Tool Tip pop up. 2. Double-click your Image to see some Glitz! 3. Click the Quit CommandButton to end your program.

C.

Verify your work. 1. Your instructor will announce whether you are to show the results of your execution on the screen and/or print the results for submission. If printing is required follow the instructions below for a different approach.

VI.

Printing Your Results.

A.

Remember the Windows Explorer Lab? — we needed to print the results shown in the Windows Explorer window and we held the [Alt] key while we tapped the [Print Screen] key. The image of the window was captured on the Windows Clip Board. We started a WordPad document and pasted the image there — and then printed it from WordPad. We will use the same technique here.

B.

Re-run your program as you did above — steps V. B. 1 and 2 — don't click the Quit button.

C.

With your application still running, hold the [Alt] key down while you tap the [Print Screen] key. The image is captured on the Windows Clip Board.

D.

Start WordPad and Edit / Paste the image into your document.

E.

Print from WordPad

F.

Close WordPad without saving the document.

G.

Back to your program — Click the Quit CommandButton to end your program.

H.

Close Visual Basic — if asked, save your files on the way out.

• • •

Place the Assessment Hand-In Sheet in your folder (with Instructor's Verification if your program was viewed). Place printout of your program execution results in your folder (if requested by instructor. Label printout as Lab VB-4 with Your Name (if printouts requested by instructor). • • •

Printouts must have your name clearly in view and be labeled as Lab VB-4. Labs must be placed in sequence in your folder. Include the Assessment Hand-In Sheet that is at the beginning of this section.

Last revised: 24-Aug-09 by djr

Assessment Exercise: Instructor Feedback Assessment includes feedback to your instructor. There are no "right" or "wrong" answers to this exercise. See your syllabus for any points associated with this portion of the VB lab exercises. Your instructor may choose to assign "points" or may make this a "gate-way" to Lab VB-4. Please use it as a means of evaluating your knowledge of Visual Basic Programming and communicating suggestions to your instructor.

Requirements: Write a short memo (in 12-Point) to your instructor with lines for: To: Your instructor's name From: Your name Date: Today's date Subject: My Feedback on Visual Basic Labs Include short paragraphs with the following information: 1. Describe your knowledge of programming BEFORE starting this set of labs. 2. Describe your knowledge of programming AFTER completing this set of labs. 3. Describe whether you understood the directions and were able to complete the labs in a reasonable length of time. 4. Describe how you "felt" about this set of labs — were they interesting? 5. Tell us how we can improve this set of labs. 6. Let us know if you think you might be interested in taking a programming course in the future — and why. Save your memo as VB ASSESSMENT in 133VB on your USB Drive. Print your memo and turn it in. Remember: There are no right or wrong answers! Thank you for giving us some feedback!

Note: Your instructor may assign additional programs to be written.

Last revised: 24-Aug-09 by djr

Suggest Documents