Introduction to Programming Using Visual Basic 6 0

Introduction to Programming Using Visual Basic 6. 0 Cheryl Klimack 729 -3900 klimack. cheryl@brandonsd. mb. ca

Why VB? Rationale… Easy for beginners to produce a working program n Capable of high end programs n Graphical n OOP (for the most part) n Affordable n Many free resources available n 2

The VB IDE View Code Menu bar View Object Project Explorer Window Tool bar Tool box Project Window Immediate Window Properties Window 3

View Menu As in all Windows applications, simply choose View from the menu to view your different toolboxes, windows, etc. or to remove them from the IDE. 4

Objects Every VB app has at least one object – the form. Other objects are added at design time by selecting the object from the toolbox and drawing it on the form. A second way is to simply double-click the object and it will appear on the form. 5

Object Properties All objects should be named. Each object has a prefix that is standard in the VB coding world. For example, the prefix for a form is frm. See the VB help for a complete list. Objects have many properties that can be accessed at design time or at run time. VB uses dot notation to access properties…for example: lbl. Message. Caption = “Welcome!” Object Property Value 6

Events An event procedure is a block of code that executes in response to an event. A user event is an action performed by the user such as a mouse click. 7

Hello World 2. Name the form frm. Hello. World 3. Type in the Caption as shown. Note it change in the title bar. 8

Hello World 4. Save the project. Create a new folder and save your form in. 5. A second dialog box will pop to ask for the Project name…change it to Hello World as shown to the right 9

Label Object 6. 7. 8. Add a label object and resize it accordingly. Change the name to lbl. Message. Change the Caption to Welcome! 10

Font Property 9. Choose the Font property and make your font larger and of a different type. 11

Alignment Property 10. Choose the Alignment property and Center the label 12

Command Button 11. 12. Add a command button by double clicking that object in the toolbox. Move it as shown. Name the button cmd. Display and change the caption to Display. 13

Done Button Add a button called cmd. Done and change the caption to Done. Note: If you choose to Copy and Paste a control, you will get a message box re: Control Array. Answer “NO” to this. 13. 14

Unload Me Adding the code Unload Me to the cmd. Done_Click event tells the computer that when the control named cmd. Done is clicked, the form (me) will unload. To run your program, choose Run from the menu, press F 5, or click the Run button on the toolbar. Clicking the Done button should unload your form. 15

Display Button The code for the Display button will make the Caption in the label lbl. Message change to “Hello, World”. 15. Double click the Display button and type in the following code: lbl. Message. Caption=“Hello, World” Run your program and click the Done button. 16

Details – Default Buttons It would be good if the user could simply hit the <Enter> key to have the message change. 16. Choose the Display button, find the Default property and set it to True. Run the program. Note the dark outline around the button indicating that it is Default. 17

Details – Keyboard Access Keys Another standard Windows feature is to be able to access a key using Alt-? . To create this ability in your program, change the Caption property to include an &. Caption for Display - &Display Caption for Done – D&one. (You can’t have them both be a D for the hotkey. 18

Moving Your Program and Creating an exe. Your program at this point will consist of three files… *. frm *. vbw *. vbp You would need to transport all 3 of these to have it work properly at a different location. 17. Create an exe by choosing File, Make Helloworld. exe. Choose your path. This one file, of course, will allow others to run your program, but not to edit it. 19

Colors We can alter the look of your form with colors and graphics. 18. Select lbl. Message. Choose the Backcolor property, then Palette. Select a color of your own choice. 19. Do the same for the Forecolor. 20

Colors on Buttons You change the color of a button’s background, but first you must set it’s Style property to Graphical. 20. Choose the Display button, then change the Backcolor and the Style property. Note that there is no Forecolor…the font stays black. 21

Message Boxes 23. In your code for the Done button, add this line: Msg. Box "Have a good day!", vb. OKOnly, "Bye Bye" 22

Comments Adding comments in VB is done by prefixing your statement with an apostrophe. For example: ‘this is a comment and will be ignored by the computer Comments turn green when typed correctly. 24. At the top of your program, add comments with your name, date, and project info as such: ‘Cheryl Klimack ‘Hello World project ‘Oct 24 2003 Run your program. We are done! 23

Pizza Project We will create the project shown to the left with checkboxes, option buttons, textboxes, message boxes, command buttons and labels. 24

1. 2. 3. Create a new project by first removing the current project. Save as Pizza. Add a label and format it as you desire. Add an image control and name it img. Pizza. The image seen here is found at G: klimackimages. Note: to resize an image on your form, you must set the Stretch property to True. 25

4. Add and name labels and textboxes to correspond to the figure at the right. Don’t worry about lining them up perfectly yet. Choose the Text property and delete it’s contents to remove Text 1 from the text boxes. txt. Name lbl. Name txt. Phone lbl. Phone 26

Aligning You can line up objects on your form evenly by selecting them (holding down the shift key allows multiple selections) and then choosing Format, Align, etc. Notice the other options under the Format menu. 5. Line up your labels and text boxes. 6. Choose both labels and text boxes at the same time, then select Font and make them all 10 or 12 point. 27

Frames are used as containers for other controls. Usually groups of option buttons are placed in frames. 7. Add a frame named fra. Size. 8. Make the Caption Size. 28

Option Buttons in Frame These are used when only one button of a group should be selected. For example, a pizza size choice cannot be both large and medium at the same time. 9. Select (but do not double click) the Option button control. Draw 3 buttons inside of the frame. Name them opt. Small, opt. Medium, and opt. Large. 10. Line them up and make the same size. Make their spacing equal as well. 29

Options on Form Options on a form but not in a frame function as a group. 11. Add options for Pickup and Delivery as shown. Set the Value for Pickup to True Note: Run the program and experiment with the buttons. If you can select 2 in one group, one of them doesn’t belong. Delete it and recreate it. 30

Multiline Textboxes with Scroll Bars 12. Add a label (lbl. Address) for Enter Address and a textbox (txt. Address) for the contents of the address. Make the Multiline property True, and set Scrollbars to Both. 31

Checkboxes allow the user to select (or deselect) an option. Any number of checkboxes in a group may be selected. If selected, it’s value is vb. Checked, otherwise it is vb. Unchecked. 13. Add a frame for Toppings (fra. Toppings). 14. Add the checkboxes indicated (chk. Pepperoni, etc. ) 32

Order and Cancel Buttons 15. Add an Order and Cancel button as shown in the figure at the right. Make the Order button Default. Add hotkey access. 33

Time to Code! The specs for this program state that the order can be cancelled at any time. After order placement, a message box will appear asking the user to verify the order as indicated. If it is verified another message box will indicate this. 34

Enabling and Disabling It is a good idea to not let the user make inappropriate choices if at all possible. Disable any options that are not applicable at the current time, and enable them when appropriate. 16. Select all the checkboxes at once and set the Enabled property to False. Run the program. 35

Enabling Controls It would be appropriate for these checkboxes to be enabled after choosing a pizza size. 17. Double click opt. Small, and add this code to the procedure. chk. Pepperoni. enabled=true Run the program. Click on Small and Pepperoni should become enabled. 18. Enable each of the checkboxes in the same manner. 36

Copy and Pasting Code 19. The code for Medium and Large will be the same as it is for Small, so you can copy and paste it into those procedures. Now choosing any of the sizes will enable the checkboxes. Choose the procedures here. 37

The Address Box We don’t need the address box if the order is for Pickup, so it should not be visible until the Delivery button is selected. 20. Choose lbl. Address and txt. Address and make Visible = false in the properties window. 38

Delivery Option Button If you choose the Delivery option, these two controls (lbl. Address and txt. Address) should become visible and the cursor should move to the txt. Address box, waiting for input. 21. Add the following to the opt. Delivery_click txt. Address. Visible = True lbl. Address. Visible = True txt. Address. Set. Focus 39

Pickup Option Button Just as Delivery should make the Address info visible, Pickup should make them invisible. 22. Add the following to the opt. Pickup_click procedure: txt. Address. Visible = false lbl. Address. Visible = False 40

Cancel Button If the user clicks the Cancel button, all the info currently entered should 'clear the text boxes disappear and the txt. Name. Text = "" form reset to the initial screen. txt. Phone. Text = "" 23. Get to the txt. Address. Text = "" cmd. Cancel_click procedure and enter the following lines of code: 41

Canceling, continued 'clear the size options opt. Small. Value = False 'clear the checkboxes chk. Pepperoni. Value = vb. Unchecked opt. Medium. Value = False chk. Sausage. Value = vb. Unchecked opt. Large. Value = False chk. Green. Peppers. Value = vb. Unchecked chk. Mushrooms. Value = vb. Unchecked chk. Extra. Cheese. Value = vb. Unchecked 'set the pickup option chk. Onions. Value = vb. Unchecked opt. Pickup. Value = True 42

Canceling, continued Last of all, disable the checkboxes again and set the focus to txt. Name. 'disable the checkboxes chk. Pepperoni. Enabled = False chk. Sausage. Enabled = False chk. Mushrooms. Enabled = False chk. Green. Peppers. Enabled = False chk. Extra. Cheese. Enabled = False chk. Onions. Enabled = False ‘set focus txt. Name. Set. Focus 43

Global Variables We are going to use some Global variables for this program. 24. Add the lines shown to your program. These variables can be used by all the procedures. 44

Constants Every time the user selects or de-selects a topping, the topping price must change. In this case, toppings are 75 cents each. 25. Constants should be declared before variables, and these are global as well, so add them BEFORE the 2 global variables you just added. 45

Topping Price We need to ADD to the cur. Toppings every time a new topping is selected, and SUBTRACT every time one is de-selected. 26. In each chk procedure, add code similar to the following, changing the Pepperoni to the appropriate topping. If chk. Pepperoni. value=vb. Checked then cur. Toppings=cur. Toppings + cur. Topping. Price Else cur. Toppings=cur. Toppings – cur. Topping. Price 46

The Immediate Window For testing purposes, you can View the Immediate window and see the results of the debug. print item statement that can be included in the code. Add this line to each chk procedure. Debug. print “Toppings =“ ; cur. Toppings When you run your program, select and de-select different checkboxes and watch the results in the immediate window. 47

Debug. Print statements Results of Debug. print 48

Size Price The size price depends upon whichever option is selected. Each option procedure needs to have code similar to the following: cur. Size = cur. Small ‘add to opt. Small cur. Size=cur. Medium ‘ add to opt. Medium cur. Size=cur. Large ‘add to 49 opt. Large

Total Price We need to calculate the total due as an addition of cur. Size and cur. Toppings. 27. Declare cur. Total as a global variable of type currency. Private cur. Total as currency in the General section. 50

Calculating the Total To calculate cur. Total, we need to add a line to every procedure that affects the price. cur. Total=cur. Toppings + cur. Size 28. Add this line to all the options for size and the checkboxes. (Thank goodness for copy and paste!) If you change your Debug. Print statement as shown, you can watch the totals as you run your program. Use Edit, Replace to do this. Also, copy and paste it to your options after the lines that calculate these totals. 29. Debug. Print "Toppings ="; cur. Toppings; "Total is"; cur. Total 51

Verifying the Order Now that we have the totals working properly, we need to manipulate some strings. We want a message box similar to the figure to appear when the Order button is clicked. 30. Declare a global variable to contain a string representing the size of the Pizza. Private str. Size as string 52

str. Size In each of the procedures for the size options, add a line to assign a string to string size that corresponds with the size. For example, in opt. Small add: str. Size=“Small” In opt. Medium, add str. Size=“Medium” & in opt. Large add str. Size=“Large”. 31. 53

Check for Required Input 32. Add the following code to verify that no required options or textboxes are left blank. We do not have time to validate the input today. Dim bln. Valid. Data As Boolean 'error checking bln. Valid. Data = False If txt. Name. Text = "" Then Msg. Box "Invalid name" txt. Name. Set. Focus Else. If txt. Phone. Text = "" Then Msg. Box "Invalid phone" txt. Phone. Set. Focus ‘to be continued 54

Run your project and click the order button with some text boxes left blank. Else. If str. Size = "" Then Msg. Box "Invalid size" opt. Small. Set. Focus Else. If opt. Delivery. Value = True And txt. Address = "" Then Msg. Box "Invalid address" txt. Address. Set. Focus Else bln. Valid. Data=True End If 55

Create a Toppings List Once we have validated entry in each required control, we can create a toppings list. Note the indenting. 33. 'list toppings in a string vb. Cr. Lf – carriage return, line feed If bln. Valid. Data = True Then If chk. Pepperoni. Value = vb. Checked Then str. Toppings = str. Toppings & vb. Cr. Lf & "Pepperoni" End If If chk. Sausage. Value = vb. Checked Then str. Toppings = str. Toppings & vb. Cr. Lf & "Sausage" & 56 concatenate

Toppings, continued Copy and paste the if …then statement for Pepperoni 5 times to create appropriate if statements for all of the toppings, as shown for Sausage. A message box can be a quick test to see if this works: Msg. Box str. Toppings 'test toppings string Delete this line once testing is completed. 57

Delivery Method The following code can be used to determine the appropriate string for the method of delivery: 34. Declare a variable str. Delivery. Method as string in the Order procedure. Then add the following to the bottom of the procedure. 'check for delivery or pickup If opt. Delivery. Value = True Then str. Delivery. Method = "Delivery" Else str. Delivery. Method = "Pickup" 58 End If

Message Boxes Revisited There are different parameters you can use with Message Boxes. See the Help for a complete list. We are going to ask the user to click Yes or No to confirm the order. We want their response to be stored so we can act upon it. If it is yes, the form should print and clear. If no, the message box should simply disappear and allow the user to make the required changes. 59

Message Box String The following code will output a message box with the appropriate strings and the Yes/No buttons. 35. First, declare a variable in the declaration section of the procedure. Dim int. Order. Correct as Integer ‘holds yes/no response from user 60

Msgbox() int. Order. Correct = Msg. Box("Order for " & txt. Name & vb. Cr. Lf _ & str. Size & "Pizza for " & str. Delivery. Method & " with" _ & vb. Cr. Lf & str. Toppings & vb. Cr. Lf & _ "Total = " & Format(cur. Total, "currency") & _ vb. Cr. Lf & _ "Is this order correct? ", vb. Yes. No, "Verify Order") _ at the end of a line means that _ the code is continued _ on the next line even though _ the statement is not finished. 61

vb. Yes, vb. No If the order is correct, print the form and clear it (the same as Canceling). If int. Order. Correct = vb. Yes Then Me. Print. Form Call cmd. Cancel_Click End if If the order is not correct, do nothing to the program. 62
- Slides: 62