Академический Документы
Профессиональный Документы
Культура Документы
Contents
Visual Basic 2005 Chapters 1-2.................................................................................................................... 3 Visual Basic 2005 Chapters 1-2 (cont.)......................................................................................................... 4 Visual Basic 2005 Chapters 1-2 Exercises..................................................................................................... 6 Visual Basic 2005 Chapters 1-2 Exercises (continued)................................................................................. 7 Visual Basic 2005 Chapter 1-2 Practice Test Taken from: http://minich.com/education/wyo/vb/basicch1/ch1_practice_test.pdf Visual Basic Name -...................................................................................................................................... 8 Visual Basic 2005 Chapter 3 ...................................................................................................................... 10 Looking at Input Using Visual Basic ................................................................................................................................................................... 10 Visual Basic 2005 Chapter 5....................................................................................................................... 22 Visual Basic 2005 Chapter 6....................................................................................................................... 31 Visual Basic 2005 Chapter 6 - Decision Structures Part 2........................................................................... 39 Ch. 6 Worksheet (If statements)............................................................................................................. 46
2|Page
Tasks are broken down into instructions that can be expressed by a computer language. Instructions = Code A program is a sequence of instructions. Programs can be only a few instructions or millions of lines of instructions
3|Page
Part VI Quick Reference To Open an existing Project Compile and Run a Program Set Properties Do This Start Visual Studio. Click Open Project on the File menu. Or On the Start Page, Click Project/Solution at the bottom of the Recent Projects Pane Click the Start Debugging button on the Standard toolbar Or Press F5 Click the object on the form whose properties you want to set, and then if the Properties window is not open, click the Properties Window button on the Standard toolbar. In the Properties window, click the property name in the left column, and change the setting in the corresponding right column Display the tool as a floating window (if it is currently docked), and resize it by dragging its edges Display the tool as a floating window (if it is currently docked), and resize it by dragging its title bar
With the mouse pointer, drag the windows title bar over a docking guide to preview how it will appear, and then release the mouse button to snap the tool into place
4|Page
Auto Hide a docked tool window Disable auto hide for a docked tool window Create a user Interface Move an Object Resize an Object Open the Code Editor Write program code Save a program Save a form file Create an .exe file
Clicked the Auto Hide pushpin button on the right side of the title bar of the tool window. The window hides behind a small tab at the edge of the development environment until you hold the mouse over it Click the tool tab, and then click the Auto Hide pushpin button
Use Toolbox controls to place objects on your form, and then set the necessary properties. Position the mouse pointer over the object until the four-headed arrow appears, and then drag the object Click the object to select it, and then drag the resize handle attached to the part of the object you want to resize Double-Click an object on the form (or the form itself) or Select a form or a module in Solution Explorer, and then click the View Code button Type visual basic program statements associated with objects in the Code Editor On the File menu, click the Save All Command. Or Click the Save All button on the standard toolbar Make sure the form is open, and then on the File menu, click the Save Command. Or Click the Save button on the Standard toolbar On the Build menu, click the Build or Rebuild command
5|Page
8.
List the steps needed to build and find and executable file in Visual Basic 2005. _____________________________________________ _____________________________________________ _____________________________________________ _____________________________________________
6|Page
Place a text box and a button on your form. When the button is clicked, display Hello World! in the text box and change the background colour of the form to blue. Add a label beside the text box and set the prompt on the label as Enter your name. The user has to enter her name in the text box before she clicks a button. A message box is used to display something like Hi there, Ally if Ally is the name that is entered. MsgBox(Hi there + TextBox1.Text) Add a date picker object to prompt the user for the date of her birthday. (Note that you can change the year quickly by just typing it in to the date picker). Your program should display the users name and birth date information by using a message box.
7|Page
8|Page
Wyo VB Ch1Proj1
Write a program that allows the user to order a certain quantity of products from your store. The user must be able to type a number into a textbox and click a button to see the total amount of money that he/she owes in a label. Place another label next to that label with a message something like "Total cost is $". You can make up the name of your store and the name of the single product that you sell. Make sure though that your program is user-friendly and attractive. You must include another button that displays the exact message "Programmed by John Doe." in a message box when clicked (but change John Doe to your name). You must also have a Clear button in the lower left of the form window and an Exit button in the lower right corner of the form window. The Clear button should at least clear the textbox. For this assignment, you do not have to rename your objects with meaningful names and appropriate prefixes. That is, your labels can be named Label1, Label2, etc. and your buttons can be named Button1, Button2, and so on. Preconditions: The user will not type in negative quantitites or quantities greater than 1000.
Staple your printouts in the following order: 1. VB code 2. The screen capture of your actual form window at runtime after a successful test case. See the instructor if you do not know how to create a screen capture. 9|Page
Slide 2
Open
Open
the online shopping program c:\vb05sbs\chap03 Double click Input Controls.vbproj or Input controls.sln If the form is not visible click the Form1.vb form in the Solution Explorer
10 | P a g e
Slide 3
Objects on the form
Radio List
Slide 4
In the Form1 section of code
'Add items to a list box like this:
Slide 5
In the ListBox1 section
'The item you picked (0-2) is held in the SelectedIndex property
Select Case ListBox1.SelectedIndex Case 0 PictureBox3.Image = System.Drawing.Image.From File _ ("c:\vb05sbs\chap0 3\inpu t controls\harddis k.bmp") Case 1 PictureBox3.Image = System.Drawing.Image.From File _ ("c:\vb05sbs\chap0 3\inpu t controls\prin ter.bmp") Case 2 PictureBox3.Image = System.Drawing.Image.From File _ ("c:\vb05sbs\chap0 3\inpu t controls\satedish.bm p") End Select
11 | P a g e
Slide 6
Also in the Form1 section
'Combo boxes are also filled with the Add method: ComboBox1.Items.Add("U.S. Dollars") ComboBox1.Items.Add("Check") ComboBox1.Items.Add("English Pounds")
Slide 7
In the CheckBox1 section
'If the CheckState property for a check box is 1, it has a mark in it If CheckBox1.CheckState = 1 Then
PictureBox2.Image = System.Drawing.Image.FromFile _ ("c:\vb05sbs\chap03\input controls\answmach.bmp")
Slide 8
Button1
'This event procedure ends the program when Quit is clicked End
12 | P a g e
Slide 9
Terminology!
What
Slide 10
Program Statement
A A
Slide 11
Keyword
A A
reserved word word that is already set aside in the programming language to do useful work
13 | P a g e
Slide 12
Variable
Like It
in Math class, a variable is used to hold a value is a container to hold data temporarily in a program
Slide 13
Object
User
interface element Examples include: Label Text Box Button Check Box etc.
Slide 14
Class
A Objects
blueprint or template for one or more objects INHERIT methods, properties and events from the class
14 | P a g e
Slide 15
Namespace
Library
System.Windows System.Diagnostics
Slide 16
Property
A
Slide 17
Method:
A
Example: ListBox1.Items.Add (Extra hard disk) Add is the method System.Drawing.Image.FromFile(H:\homer.bmp) FromFile is the method
15 | P a g e
Slide 18
To Do
Check Write
out the greetings.exe program on the S drive a visual basic program to do the same tasks. When your program is complete and correct, be sure to add comments Create an exe file out of your VB project.
Chapter 3
1.
2. box?
What part of the design view on the form do you double-click in order to enter items on a list ______________________________.
3.
What part of the design view on the form do you double-click in order to enter items on a ______________________________.
combo box? 4.
What part of the form is double-clicked when you want to use the case statement based on the ______________________________.
16 | P a g e
6.
Keyword
Variable
Object
Class
Property
Method
17 | P a g e
Assign a short-cut key Change the order of menu items Add a toolbar to your program Use a standard dialog box in your program Display an Open dialog box Display a Color dialog box
Part A. Working with Menus 1.Place a menu called Clock with two menu commands, Date and Time.
18 | P a g e
1. Assign each menu item an access key. Use the first letter of the item if possible, or the access key that is commonly assigned (Such as For eXit). In this case, use C for Clock, D for Date and T for Time. Also, set the shortcut keys for each of the menu items. (See the property Shortcut Key for each menu item. 2. Change the order of menu items by dragging the Date menu on top of the Time menu 3. Add a Label to for information display and set AutoSize to be False and BorderStyle FixSingle and Text Empty and TextAlign to MiddleCenter 4. Double-Click the Time command in the menu, Type the following statement in the TimeToolStripMenuItem_Click() Label1.Text = TimeString displays the current time from the system clock 5. Double-Click the Date command in the menu, Type the following statement in the DateToolStripMenuItem_Click() Label1.Text = DateString displays the current time from the system clock 6. Run the program 7.
19 | P a g e
System Clock Properties and Functions 8. TimeString This property returns the current time from the system clock. DateString This property returns the current date from the system clock. Now This property returns a value representing the current date and time. Hour(date) This function extracts the hour portion of the specified date/time value. See example below Minute(date) This function extracts the minute portion of the specified date/time value. Second(date) Similar to the minute function, only it returns the second Year(date) Similar to the minute function, only it returns the year
Part B Working with Toolbars 1. Insert a toolbar control to your form 2. Click the tiny shortcut arrow in the upper-right corner the new toolbar to insert standard items 3. Click the add ToolStripButton button on the right side of the toolbar. Right-click the new button and set Display Style as Image and Text. Then Change the Text property to Color and set Image of the button by using a bitmap file under chap04 4. You may move or delete toolbar buttons
20 | P a g e
1. Add, the ColorDialog and the picture box to your form. 2. Double-click the Color button 3. Type the following program in the colorToolStripButton_Click
ColorDialog1.ShowDialog() Label1.ForeColor = ColorDialog1.Color
4. Run the program to test the code 5. Click the Save All button and build an executable File.
21 | P a g e
Slide 1
Ch5. Variables and Numbers
Visual Basic 2005
Slide 2
Agenda
Assignment Operator Arithmetic Operations Variables Incrementing the Value of a Variable Built-In Functions: (examples)
22 | P a g e
Slide 3
Agenda (contd)
The Integer and Double Data Type Multiple Declarations Parentheses Three Types of Errors
Slide 4
Assignment Operator
Label1.Text = Hello World! Means let the text content of Lable1 be Hello world. Textbox1.Visible = false Means let Textbox1.visible be false.
Slide 5
Arithmetic Operations
Five arithmetic operations in Visual Basic
___________________________________
+ addition - subtraction * multiplication / division ^ exponentiation
23 | P a g e
Slide 6
More Arithmetic Operators
___________________________________
\ whole number division [cuts off the decimal partit does not round off] 13 \ 5 2 whereas 13 / 5 2.6 [normal division] remainder division 13 divided by 5 = 2 remainder 3 therefore 13 mod 5 3 string concatenation
mod
&
Slide 7
Numeric Expressions
2+3 3 * (4 + 5) 2^3
Slide 8
Numeric Variable
A numeric variable is a name to which a number can be assigned.
Examples: speed distance interestRate Balance Numeric Expressions: speed = 3*8 distance = speed * time
24 | P a g e
Slide 9
Parentheses
Parentheses should be used liberally in numeric expressions. In the absence of parentheses, the operations are carried out in the following order: ^, * and /, + and -. BEDMAS
Slide 10
Variables
___________________________________
Declaration:
Dim speed As Double
Variable name Data type
Assignment:
speed = 50
Slide 11
Integer Data Type
Variables of type Double can be assigned both whole numbers and numbers with decimals. The statement Dim varName As Integer declares a numeric variable that can only be assigned whole number values between about -2 billion and 2 billion.
25 | P a g e
Slide 12
Open data types program
Open the VB program data types from the chap05 folder Run it.
Slide 13
Three Types of Errors
Syntax error Run-time error Logic error
Slide 14
Some Examples of Syntax Errors
Misspellings Lable1.Text=hello Omissions result = 2 + Incorrect punctuation Dim m; n As Integer
26 | P a g e
Slide 15
A Run-Time Error Example
___________________________________
Overflow error
Slide 16
A Logical Error Example
Dim average As Double Dim m As Double = 5 Dim n As Double = 10 average = m + n / 2 Value of average will be 10. Should be 7.5.
Slide 17
Lab1: A basic Calculator
27 | P a g e
Slide 18
Coding the button
Slide 19
Using variables
___________________________________
Set aside space for variables
Dim LastName as String
Slide 20
Example A
Open the Variable Test project in \chap05\variable test folder Double-click the Show button to type the following statements:
28 | P a g e
Slide 21
Variable Naming Conventions
Begin each variable name with a letter or underscore. Variable names can only contain letters, underscore, and numbers. Make your variable names descriptive by combining one or more words, e.g. SalesTaxRate Capitalize the first letter of each word of the variable names. Dont use Visual Vasic keywords, objects or properties as variable names. If you do, you will get an error when you try to run your program.
Slide 22
Example B:
___________________________________
Which of the following variable names are correct?
Good-by shrift Double thisMustBeTooLong Textbox1 8ball
Slide 23
Using a variable to store Input
A textbox and a listbox can be used to gather user input. Another way to gather input is to use the InputBox function to display a dialog box on the screen and then use a variable to store the text the user types.
29 | P a g e
Slide 24
Example C
Open the Input Box in the \chap05\input box folder Double-click the Input Box button and type the following program Dim Prompt, FullName As String Prompt = Please enter your name. FullName= InputBox (prompt) Label1.Text = FullName or MsgBox (FullName, Input Results)
Slide 25
Lab
Write a program that allows the user to enter a noun into one input box, a verb into another input box and an adjective into a third input box . The program stores the information user entered in three different String variables subInput, verbInput, objInput. You may include more input boxes with prompts such as "place", "food", "animal", etc.
Slide 26
Lab (cont.)
___________________________________
Include a button with the Text property "Click" that displays a funny mad lib in a message using the three or more user inputs.The label should initially be invisible but become visible when the user clicks the Click button. Also include an Exit button that the user can click to end the program. In order to add line breaks in the output in the label, use the vbCrLf constant as in Label1.Text =subInput + vbCrLf + verbInput + vbCrLf + objInput
30 | P a g e
Slide 27
Lab 2
___________________________________
Write a program that gets three test scores from the use and displays her average.
Slide 1
Ch6. Using Decision Structures
Visual Basic 2005
31 | P a g e
Slide 2
Agenda
Review Chapter 5 If then else decision structure If-without else Nested ifs Lab: a trivia quiz
Slide 3
Variables
The two statements above are equivalent to Dim Age As Integer =10
Slide 4
32 | P a g e
Slide 5
Slide 6
Translate into VB
Dim Destination As________ Destination = InputBox(Enter your destination:) If Destination exit 456 Else go straight ahead End if = Bismarck then
Slide 7
If Block
The program will take a course of action based on whether a condition is true. If condition Then action1 Else action2 End If
33 | P a g e
Slide 8
Flow chart for if-else
true false
Condition
Action 1
Action 2
Flow chart: A graphic representation of the logic or steps in a program or system. A flowchart represents how a program or activity moves through various processes or program routines. It uses symbols to represent the activities, and it uses arrows to represent the direction of activity through the processes. Flowcharts can be used to define the behavior of a single program or a system (a combination of programs).
Slide 9
Example 1: Find the larger number
TextBox1 TextBox2
Label1
Slide 10
Example 1: Code of button1_click
Dim num1, num2, largerNum As Double num1 = ______________________ num2 = ______________________ If num1 > num2 Then largerNum = ________ Else largerNum = ___________ End If Label1.Text = "The larger number is " +__________
10
34 | P a g e
Slide 11
Example 1: Output
11
Slide 12
ElseIf clause
If condition1 Then action1 ElseIf condition2 Then action2 ElseIf condition3 Then action3 Else action4 End If
An extension of the If block allows for more than two possible alternatives with the inclusion of ElseIf clauses. Note: there is no space between the word "Else" and "If" Only one "End If" is required.
12
Slide 13
Flowchart for if-else- if
expr 1
false true
block 1
expr 2
false false
true
block 2
expr N
false
true
block N
default block
13
35 | P a g e
Slide 14
Mark>= 90 -----A+ Mark> =80 -----A Mark >= 70-----B Mark> = 60-----C Mark>=50------D Mark<50-----F
Slide 15
Flow chart for if with no else
Condition
true Action 1
false
Action 2
15
Slide 16
Catch the bug
Dim Destination As String Destination = InputBox(Enter your destination:) If Destination exit 456 End if go straight ahead = Bismarck then
16
36 | P a g e
Slide 17
What will be displayed in Lable1?
Dim Age As Integer Age =TextBox1.Text If Age >= 16 then Label1.Text= You can drive. End if Label1.Text= You are too young to drive.
Slide 18
What will be displayed in Lable1?
Dim Age As Integer Dim Message as String Age =TextBox1.Text Message = You are too young to drive. If Age >= 16 then Message= You can drive. End if Label1.Text=Message
Slide 19
Nested If Blocks
When one If block is contained inside another If block, the structure is referred to as nested If blocks. Care should be taken to make If blocks easy to understand.
19
37 | P a g e
Slide 20
Simplified Nested If Statement
If cond1 Then If cond2 Then action End If End If If cond1 And cond2 Then action End If
Nested If
Less Confusing
20
Slide 21
Lab: a trivia quiz
Combo box for question selection Textbox for question display Radio buttons for options When the check button is click, a message box pops up telling whether the answer was correct or not.
Slide 22
Double clicked the combo box
If ComboBox1.Selec tedItem = "Country" Then TextBox1.Text = " Which country am I going to visit this summer?" RadioB utton1.Text = "Canada" RadioB utton2.Text = "Italy" RadioB utton3.Text = "China" RadioB utton4.Text = "France" ElseIf ComboBox1.SelectedItem = "Flower" Then TextBox1.Text = "Which of the following is my favorite flower? " RadioB utton1.Text = "Lilly" RadioB utton2.Text = "Rose" RadioB utton3.Text = "Daisy" RadioB utton4.Text = "Ginge r Flower" ElseIf .
38 | P a g e
Slide 23
Double Click the Check Button
If ComboBox1.SelectedItem = "Country" Then If RadioButton1.Checked = True Then MsgBox("You got it!") Else MsgBox("Wrong!") End If End If Improved version
If ComboBox1.SelectedItem = "Country" AND RadioButton1.Checked = True Then
MsgBox("You got it!") Else MsgBox("Wrong!") End If
39 | P a g e
Slide 2
Agenda
Relational Operators Logical Operators Incrementing a variable Lab: A Guessing Game
Slide 3
Relational Operators
< <= > >= = <> less than less than or equal to greater than greater than or equal to equal to not equal to
Slide 4
Relational Operator Notes
Relational operators require an
operand on both sides of the operator Value of a relational expression will always be True or False Expressions are evaluated from left to right with no order of operations
40 | P a g e
Slide 5
Logical Operators
Used with Boolean expressions Not makes a False expression True and vice versa And will yield a True if and only if both expressions are True Or will yield a True if at least one of both expressions are True
Slide 6
Example
To test if n falls between 2 and 5: (2 < n ) And ( n < 5 ) To test if n falls outside the range from 2 to 5 _________________ A complete relational expression must be on either side of the logical operators And and Or.
6
And and Or are binary operators requiring two operands Not is a unary operator requiring only one operand
Slide 7
Syntax error
The following is NOT a valid way to test if n falls between 2 and 5: (2 < n < 5 )
41 | P a g e
Slide 8
A common error is to replace the condition Not ( 2 < 3 ) by the condition (2>3) The correct replacement is ( 2 >= 3 ) because >= is the opposite of <, just as <= is the opposite of >
Slide 9
Skills Check
Assume that x = 1 and y = 13 (x > 0) evaluates to _____ (x <> 1) evaluates to _____
((x > 5) Or (y <= 20)) evaluates to____ ((Not (x = 12)) And (y = 13))evaluates to___
Slide 10
Boolean Variable
A variable declared with a statement of the form Dim Var As Boolean is said to have Boolean data type. It can assume just the two values True and False. Example: Dim BoolVar As Boolean BoolVar = 2 < 6 TextBox1.Text = BoolVar displays ______in the text box.
10
42 | P a g e
Slide 11
Incrementing a variable
Dim Score as Integer=0 0 Before Score If radiobutton1.checked=true then Score=Score+1 Reads the current value of score 1 After Score End if Label1.Text = Score
displays the score in label1
Slide 12
Lab: A Guessing Game
Declare a variable to hold the random number generated by the computer Declare another variable to hold the users guess
Slide 13
Variable declaration
Public Class Form1 Dim Num As Integer Dim Guess As Integer Then double click the form to type the following statements inForm1_Load Randomize() Num = __________ assign a random number from 1 to 10
43 | P a g e
Slide 14
Code for the click button
Assign the text of textbox1 to the variable guess If guess equals to num then MsgBox ( Congratulations) Else MsgBox(Wrong! The number is & num End if
Slide 15
An improved version
To keep track of how many tries the user has had, a new variable named tries has to be introduced. Each time, when the Click button is clicked , increment the value of tries
Slide 16
Coding
Add a variable declaration under Public Class Form1 Dim Tries As ________=____ Modify the code of the button1_click
Increment tries If tries <=3 then If num=guess then display congratulations Else display wrong! Try again End if Else display You lose, the number is& num End if
44 | P a g e
Slide 17
A more-complicated version
Write a more complicated guessing game. Now the program is to write "cold" when the guess is 3 or more away from the correct answer, "warm" when the guess is 2 away, and "hot" when the guess is 1 away.
45 | P a g e
46 | P a g e
Part B 1. Write an If statement that displays "yes" in the label named Output if intSum is greater than 5.
2. Change the If statement that you used in your answer to #1 into an If Else statement so that it also displays "no" in the label if intSum is not greater than 5.
3. Write an If ElseIf statement that: -displays the message "greater than 5" in Output if intSum is greater than 5, -displays the message "equal to 5" in Output if intSum is equal to 5, -and displays the message "less than 5" in Output in all other cases.
4. Write a plain If statement that displays "yes" in Output if intSum is greater than or equal to 1 and intSum is less than or equal to 100.
47 | P a g e
5. Write an If statement that displays "Please try again" in Output if intUserInput is not greater than or equal to 1 or intUserInput is not less than or equal to 100.
6. Describe the logical error that you see in the If ElseIf statement below: If (dblGrade >= 60) Then lblGrade.Text = "D" ElseIf (dblGrade >= 70) Then lblGrade.Text = "C" ElseIf (dblGrade >= 80) Then lblGrade.Text = "B" ElseIf (dblGrade >= 90) Then lblGrade.Text = "A" Else lblGrade.Text = "Logical error occurred." End If THE END!
48 | P a g e