Week 09 & 10
Week 08
Week 07
Week 05 & 06
Week 04
Week 03
Week 02
Week 01
Week 11
Objects
Any of the controls on a form are objects
Most of them have properties and methods
Buttons we draw on a form are objects
Created from classes
They are an instance of a class
Not all objects are visible
Classes
Are the blueprint or template used to create objects
There are many intrinsic classes in VB.net
You can create your own class
Object Oriented Programming
Is a way to program, it is a strategy
Allows use to reuse methods and code
Encapsulation: Let's use put all properties, methods, events into one package
Creating our own Class
You create the properties and methods
Properties are created using variables and data definitions
Methods are created using sub-procedures or functions
1- create class
2- add variables
3- add properties
4- add methods
1-
Public Class Booksale
End Class
2-
Private m_titleString As String
Private m_quantityInteger As Integer
Private m_priceDecimal As Decimal
3-
Public Property Title()As String
Get
Return m_titleString
End Get
Set(ByVal Value As String)
m_titleString = Value
End Set
End Property
4-
Public Function ExtPrice()As Decimal
Return m_quantityInteger * m_priceDecimal
End Function
Constructors
You would create a constructor to intialize your object
You might open a connection to a database or set some properties
Sub New() is always the name of the constructor
'code in the form
mBookSale = New Booksale(titleTextbox.text, quanTextbox.text)
' this calls the Sub New sub-procedure in the class and
' passes it two values
'code in the class
Sub New(Title as String, Quantity as Interger)
m_titleString = Title
m_quantityInteger = Quantity
End Sub
'in this example the Sub New() takes the two
'values passed to it and sets the title property
'and the quantity property
Week 09 & 10
Select Case
' Determine the age and display the appropriate label
Select Case ageInteger
Case Is < 60
displayLabel.Text = "Cold"
Case 61 To 72
displayLabel.Text = "Moderate"
Case Else
displayLabel.Text = "Hot"
End Select
Case Is > 6
Case 300 to 600
Case 1, 3, 5, 7
Case “Pigs”
Case “Andy”, “Bob”
Case Else (optional)
Arrays
List or Series of values
When you need to store multiple values
List or series of values, like a combo or listbox BUT with no visual
representation
Similar to a single variable
Dim scoresInteger(4) as Integer
Dim m_numbersInteger() as Integer = {1 , 3 , 5 , 7 , 9 , 11}
Dim animalsString() as String = {“Tiger”, “Elephant”, “Mouse”}
Dim scoresInteger(4) as Integer | | | Array name | Data Type Index (subscript)
Referencing an element in an array
displayLabel.text = m_numbersInteger(4)
displayLabel.text = m_destInteger(intX)
Sorting, Reversing an array
Array.Sort(m_destInteger)
Array.Reverse.(m_numbersInteger)
Determining the size of an array
sizeArrayInteger = UBound(scoresInteger)
For Each Next Loop to look through an array (m_numbersInteger in
this example)
Dim indNumInteger, totalNumbersInteger As Integer
For Each indNumInteger In m_numbersInteger
totalNumbersInteger += indNumInteger
Next
lblD.Text = FormatNumber(totalNumbersInteger / counterInteger)
Structure
Used to collect different data types together
Person’s name, GPA and age
'Declarations area (module)
Structure Student
Dim nameString As String
Dim gpaDecimal As Decimal
Dim ageInteger As Integer
End Structure
Dim m_indStudent As Student
'Local level
m_indStudent.nameString = nameTextbox.Text
m_indStudent.gpaDecimal = Cdec(gpaTextbox.Text)
m_indStudent.ageInteger = CInt(ageTextbox.Text)
Structure of an Array
'Declarations area (module)
Structure Student
Dim nameString As String
Dim gpaDecimal As Decimal
Dim ageInteger As Integer
End Structure
Dim m_indStudents(20) As Student
Dim m_counterInteger as Integer
'Local level
m_indStudents(m_counterInteger).nameString = nameTextbox.Text
m_indStudents(m_counterInteger).gpaDecimal = Cdec(gpaTextbox.Text)
m_indStudents(m_counterInteger).ageInteger = CInt(ageTextbox.Text)
m_counterInteger += 1
Match in a ComboBox
'For Next loop to move through each item in productsComboBox
For countInteger = 0 To productsComboBox.Items.Count - 1
If CStr(productsComboBox.Items(intCount)).ToUpper = productsComboBox.Text.ToUpper Then
'if there is a match change
'matchBoolean to true and exit loop
matchBoolean = True
Exit For
End If
Next
'Check to see if there is a match
'if no match then add user input
If matchBoolean = False Then
productsComboBox.Items.Add(productsComboBox.Text)
Else
MessageBox.Show("This item already exists", "Error:Match",
MessageBoxButtons.OK)
End If
Week 08
Multiple Forms
You can create a second form that is called from the original form
'code in the first form
aboutForm.Show() ' reveal the object
You can "push" information to the 2nd form from the 1st form
aboutForm.displayTextbox.text = "This is the 2nd form"
For/Next Loops
Used if you know how many loops you want to execute
3 steps
Intialize counter
Increment counter
Test the counter
Intialize counter & Test the counter
|
For LoopIndex = IntialValue To TestValue
‘Code
Next LoopIndex
|
Increment counter
3 elements
LoopIndex : counter variable
InitialValue : value the counting(looping) starts at
TestValue : value that ends the looping
i.e.
For countInteger = 0 To 7
' Code
Next countInteger
You can define the increments using Step
For countInteger = 0 To 7 Step 2
' Code (This loop will have 4 iterations)
Next
You can use variables for the end and step. You will need to Dim the variables
Dim countInteger, endInteger, stepInteger as Integer
endInteger = 7
stepInteger = 2
For countInteger = 0 To endInteger Step stepInteger
'Code
Next
For xInteger = 2 to 100 Step 2
For yInteger = stepInteger to endInteger Step stepInteger
For zInteger = 0 to fruitCombobox.Items.Count - 1
For dInteger = (X – 5) to mInteger
For yDecimal = 0.5D to 0.25D Step 0.05D
For sInteger = 10 to 0 Step -1
For countInteger = 0 To 6
will loop 7 times
For countInteger = 1 To 6
will loop 6 times
For countInteger = 0 To 6 Step 2
will loop 4 times
For countDecimal = 0 To 6 Step .5d
will loop 13 times
For countInteger = 6 To 0 Step -1
will loop 7 times
The IntialValue, TestValue and Step can be constants, variables, literals,
expressions
You can not change TestValue and Step in the loop
The default Step is 1
To Uppercase
UCase(productsComboBox.Text)
UCase(CStr(productsComboBox.Items(countInteger)))
Week 07
List and Combo Boxes
Controls for presenting the user a number of choices
You can allow the user to add text
Or restrict the user from adding text to the boxes
Enter items into list boxes using the Items collection in the Properties window.
Add and remove items in a list at run time.
Determine which item in a list is selected.
Use the Items.Count property to determine the number of items in a list.
Display a selected item from a list.
Use Do/Loops to iterate through a loop.
No Text Added |
Text Added |
|
List Box |
Combo Box
DropDownStyle – Simple
|
Large Footprint |
Combo Box
DropDownStyle - DropDownList |
Combo Box
DropDownStyle – DropDown |
Small Footprint |
List box - User can NOT add text
List box - Control can be stretched to large size
Combo box - Has Drop Down Style property
Properties
Items (Index Number)
Text (combo box only)
Sorted (set to true or false)
Count (countInteger = moviesListBox.Items.Count)
DropDownStyle (combo box only)
Simple (User can add text, can be large)
Drop Down (User can add text, is smaller)
Drop Down List (User can NOT add text, is smaller)
Methods
Add (an entry into a ComboBox)
fruitComboBox.Items.Add(entryTextbox.text)
fruitComboBox.Items.Add(fruitString)
fruitComboBox.Items.Add(fruitComboBox.Text)
Remove and RemoveAt (Remove an entry from the List or Combo Box)
namesListBox.Items.Remove("Harold")
statesComboBox.Items.Remove(statesComboBox.Text)
statesComboBox.Items.RemoveAt(statesComboBox.SelectedIndex)
namesListBox.Items.RemoveAt(1)
Select (Highlight or display a specific entry)
fruitComboBox.SelectedIndex = 3
fruitComboBox.SelectedIndex = -1 (to deselect all items)
Clear (out all entries, very dramatic)
namesListBox.Items.Clear()
To reference (a Combo or List Box entry)
displayLabel.Text = fruitComboBox.Items(indexInteger)
displayLabel.Text = fruitComboBox.Text
Do Loops
Used in relation to a condition
How many times will it loop? \ The same question
How many times will it execute? /
How many iterations will it have? /
Do While Loops Pretest and Posttest
Do While X < 5
X = X + 1
Loop
Do
X = X + 1
Loop While X < 5
Do Until Loops Pretest and Posttest
Do Until X = 7
X = X + 1
Loop
Do
X = X + 1
Loop Until X = 7
Loops end based on a condition YOU set
You are responsible for incrementing the counter
Post Tests have at least one iteration
Dim X as Integer
Do Until X = 3
X = X + 1
Loop
X out |
# Loops |
X in |
0 |
1 |
1 |
1 |
2 |
2 |
2 |
3 |
3 |
3 |
X |
|
Endless Loops
Do Until X > 7
X = 1
Loop
Week 05 & 06
Procedures
There are 2 types of procedures
Procedures
/ \
Sub-procedures Functions
Performs actions Performs actions
Returns a value
Where do you put procedures?
How do you call them?
Why use them?
Sub-procedures
This line of code within your code
Warning()
Calls this sub-procedure
Private Sub Warning()
displayLabel.text = "Warning"
End Sub
Functions
This line of code within your code...
commissionLabel.text = Commission(weeklySalesDecimal)
^ ^ ^
value returned here name argument
...calls this function
Name argument return data type
| | |
Private Function Commission(salesDecimal as Decimal) as Decimal
Commission = salesDecimal * 0.15D
End Function
Private Function Commission(ByVal salesDecimal as Decimal) as Decimal
They return to where they left
Procedures can have arguments that are literal values, variables, or properties
displayLabel.text = Cal( 25 , intNumber , txtName.text)
Arguments
Order
Number of arguments
Data Type
(Name does not matter)
What are you passing in?
How are you manipulating it?
What are you returning?
You can return any data type in a function
You can use either of the following for a function
Commission = salesDecimal * 0.15D
Return salesDecimal * 0.15D
To create a procedure ask these questions
1. What is the procedure going to do?
2. What is it’s unique name?
3. Does it need any data?
4. Will it return any value?
5. What will the calculations be?
6. What will it’s logic be?
7. How and when do I call the procedures?
Menus
Menus are created in design time
mnu is the naming convention for the control
Each item on a menu is a control
Menu items have click events
Note: make sure the menu property on the form is switched on
Dialog Boxes
Need to place on form from toolbox.
Need to name
Typical dialog boxes
Font
Color
Print
OpenFile
SaveFile
PrintPreview
the naming convention
colorDialog
Code example:
' This code will open the dialog box for the user to choose a color
colorDialog.ShowDialog()
' This code applies the color property of the dialog
' box (the color the user chose) to the controls ForeColor property
displayLabel.ForeColor = colorDialog.Color
You can set initial values on a dialog box
dlgColor.Color = displayLabel.ForeColor
Note: Enabling a property during run time
Week 04
If Statements
If totalInteger=100 Then
'code if the condition IS met
End If
If priceDecimal>25 Then
'code if the condition IS met (TRUE)
Else
'code if the condition is NOT met (FALSE)
End If
Relational Operators
=
>
<
>=
<=
<>
Nested If's
If tempInteger <=32 Then
label = "Freezing"
Else
If tempInteger > 80 Then
label = "Hot"
Else
label = "Moderate"
End If
End If
-OR- ElseIf
If tempInteger <=32 Then
label = "Freezing"
Elseif tempInteger > 80 Then
label = "Hot"
Else
label = "Moderate"
End If
Note: If you use Elseif you only use ONE End If
Input Validation
You can validate information in a textbox
Number - Is the value a number
If IsNumeric(userAgeTextbox.text) Then
Range - Does the value fall within a range
If userAgeTextbox.text >0 AND userAgeTextbox.text <150 Then
Required field - Is the textbox filled out?
If userAgeTextbox.text <> "" Then
Debugging
Nesting
Compound Conditions
NOT
AND
OR
If varInteger > 0 AND varInteger < 10 Then
'code if BOTH conditions are met
End If
If varInteger = 5 OR varInteger = 8 Then
'code if EITHER condition is met
End If
If NOT varInteger = 2 Then
'code if varInteger is not the value of 2
End If
If ___T___ And ___F___ Or ___T___ Then
| | |
-------------
F T
| |
------------------
T
Message Box
MessageBox.Show("Text", "Title", [Button options])
Message Box Options
Buttons:
Ok (default)
Ok Cancel
Yes No
Yes No Cancel
-others-
Icons:
Exclamation
Warning
Error
Question
-others-
MessageBox.Show("Text", "Title", MessageBoxButtons.YesNo,
MessageBoxIcon.Exclamation)
Radio Buttons : Use nested If's or If/ElseIf statements
If blueRadio.Checked = True Then
testLabel.BackColor = Color.Blue
ElseIf greenRadio.Checked = True Then
testLabel.BackColor = Color.Green
ElseIf yellowRadio.Checked = True Then
testLabel.BackColor = Color.Yellow
End If
Checkboxes: Each Checkbox needs it's own If Statement
If fmCheckbox.Checked = True Then
m_carPriceDecimal += 100
End If
If cdCheckbox.Checked = True Then
m_carPriceDecimal += 50
End If
If mp3Checkbox.Checked = True Then
m_carPriceDecimal += 25
End If
Note: You can assume that the condition is true in conditionals
If radioCheckbox.checked = "true" Then
- is the same as -
If radioCheckbos.checked Then
Expand Plan Solution step
- Define Problem
- Plan solution
- What is your
input?
- What is your
output?
- Objects
- Events to
recognize
- Calculations
- Variables
- Constants
- Design interface
- Code and Comment(Pseudo
Code)
- Debug
Week 03
| Order
of Precedence and Math |
|
| () Parentheses |
(A
+ B) * 2 |
| ^ Exponentiation |
2^3
is 2 to the 3rd power |
| - Negation |
-2
+ 3 |
| *,/ Multiply,
Divide |
3
* 4 / 5 (execute left to right) |
| \ Integer
Division |
120
\ 60 = 2
150
\ 60 = 2
30
\ 60 = 0 |
| Mod Remainder |
120
Mod 60 = 0
150 Mod
60 = 30
30
Mod 60 = 30 |
| +,- Addition,
Subtraction |
3
+ 4 – 5 (execute left to right) |
No implied operations
| Math
2A
2(A + B) |
VB
2 * A
2 * (A +
B) |
Formatting output
FormatCurrency(totalDecimal, 2)
FormatNumber(sumDecimal, 4)
FormatPercent(resultDecimal, 0)
Standard for Homework
(website)
- Formatting output
- Option Strict
Note:VB is
case sensitive but it will transform keywords into a standard case
New Objects
Textboxes
Radio Buttons
Check Boxes
Group Boxes
New Properties
Tab Index
Tab Stop
Visibility
Checked
Declaring a Constant
Const TAX_RATE_decimal as Decimal = .15D
Intrinsic Functions
Functions established by Visual Basic require an argument
CInt(userNumberTextbox.text)
CInt is the function and
userNumberTextbox.text is the argument
Other functions
CDec() converts value to a decimal
or Decimal.Parse()
CInt() converts value to an integer
or Integer.Parse()
CStr() converts value to a string
Note:The CInt and CDec functions will not convert an empty text box
into a value.
Week 02
Variable Scope (the lifetime of a variable)
How long is the
life of your variable?
Local or Module
is defined by WHERE you Dim the variable
Local
- within Sub procedures
Module
- within a form
Local – Used in
just a sub procedures. Gets reinitialized every running
Module – Used anywhere
in the code.
Running
Totals
Counter
These variables
must be declared as module-level variables. If counters and accumulators
are declared as local variables they will be initialized to zero each time
the event occurs. Variables and constants that must be used in more than
one procedure of a form must be declared as module-level.
Note: you can set properties in Design time or at Run time
Concatenating
To connect strings you us the "&" symbol
messageString = "Hello " & "Mike"
messageString = "Hello " & nameString
messageString = "Hello " & nameTextbox.text
Select multiple controls and move them, align them, and set common
properties
.exe file is created in bin
Variables & Constants
Temporary memory locations to hold values
Variables can be changed and manipulated
Constants can not change
Data Types (how to choose/ memory size)
Integers (4 bytes) -2 billion to +2 billion
Decimals (16 bytes) up to a lot of decimal spaces
String (varies)
Boolean(2 bytes) true/false
Declaring a Variable
Dim totalInteger as Integer
Dim priceDecimal as Decimal = 7.55
Dim gradeDecimal, avgDecimal, gpaDecimal as Decimal
Use D and I
Const TAX_RATE_decimal as Decimal = .15D
bonusInteger = CInt(salesTextbox.text) + 150I
Naming Conventions and Rules
Conventions:
Relevant
Case
Rules:
Yes:
Yes letters (start)
Yes digits (can't start with a digit)
Yes under score
No spaces
NO periods
No keywords
decTaxRate_15
^ ^
data type / relevant name
Where are you? Are you lost in the code? Design view, code view, run
time, design time?
Writing code
Surmise what your problem is
Create a solution
Develop an interface
Recognize the events that will take place at the users end
i.e. Button pushed, checkbox checked, text entered in textbox
Sketch out actions that will be part of each event
Write code for each of those actions
Intell-i-sense
Properties -
(Name): is used to refer to the control in the Basic code.
Text: determines what will appear on the form for a Label control.
lblDisplay.Text = “Hello World”
^ ^ ^
object property value
Time
Design
Run
Break
File Management
How to zip
How to Submit
Week 01
Programming Languages intro
Input> Processing > Output
Creating an application in Visual Studio
Create project> Windows App
Choose location (Do not program on the network)
Name project (naming conventions)
Design Form
Add objects and adjust properties
Name and Text property
Code events
Change form name and text properties
Change startup object for the project
Naming conventions
How to Save a project
How to Close a project
How to open an existing project
Do Not work on the network
Visual Studio Interface
Properties window
Solution Explorer
Toolbox
Design view
Code view
Standards for Homework (website)
• Description
• Comments
• Readable
Steps for creating an computer program
1) Define problem
2) Plan solution
3) Design interface
4) Code and Comment
5) Debug
Define problem example
I need to figure out the sales tax on this sale
Need to know how fast that car is moving
Need to determine what my grade is
Code – Assignment statements & Remark statements
Samples of Assignment Statements
displayLabel.Text = “Hello World”
displayLabel.Text = txtName.Text
displayLabel.ForeColor = Color.Blue
displayLabel.Visibility = True
nameTextbox.Text.Clear()
Remark statements also known as Pseudo code or Comments
Sample of Comments
'Capture the score
gradeInteger = CInt(gradeTextbox.Text)
Declarations
The Declarations section is located at the top of the file, above all
of the code in the procedures. It is a good location for remarks that
identify the project name, the programmer name, the date the project
was created, and a description of the project.
In using an assignment operator
VB evaluates the value on the right
and assigns it to the property on the left
totalInteger = costInteger * 1.2
finalDecimal = gradeDecimal / attendanceDecimal
resultDecimal = discountDecimal + CDec(priceTextbox.text)
Heirarchy of Solution in Visual Studio
Solution will have one or more
\
Projects will have one or more
\
Forms will have one or more
\
Objects all have
/ | \
Properties Methods Events
|