Wyo VB Ch. 2 Lecture Notes
Objective #1: Use forms appropriately.
- A form is a basic building block of a
Visual Basic project. Eventually, you'll be creating projects that consist
of many forms. You'll also learn how forms can be reused to save programming
time and to give more consistency to a large project.
- Each form is really a class which we will study in more
detail later. Usually, a class consists of many methods.
Some methods are related to user events such as click and keypress.
- A form has number of useful properties including the Text property.
It is best to set the Text property of a
form to an appropriate phrase. The form's Text property
appears in the blue title bar at the top of the form.
- The first default form of a VB project is often saved
with the file name of Form1.vb. The class that goes along with this
form is also named Form1. For now in this
VB course, it is not recommended that you change the this file name or that
you rename the class even though it does
not
begin with
the conventional
form prefix frm.
- You can think of a form as having two basic parts, its
interface and its code. The interface is what the user will see when he/she
executes the program. The code is the behind-the-scenes part of the form
that contains the crucial logic and code that makes the form work that way
the programmer intends it to work.
- A form and the objects on a form are measured in pixels.
The size of the pixels on your monitor depend on your computer's screen resolution
settings. Popular screen resolution settings are 640 pixels by 480 pixels,
800 pixels by 600 pixels, or 1024 pixels by 724 pixels where the first number
is the width of the screen and the second measurement is the height of the
screen. Larger numbers of pixels in the resolution means the screen looks
sharper with more detail. For now in this course, it is not recommended that
you resize a form to make it fill up more of the computer screen.
- The Size property of
a form is used to determine its size. Actually, it is the two subproperties, Height and Width,
of the Size property that determine the
size of the form. The Location property
of a form is used with its two subproperties, X and Y,
to determine the location of the upper-left corner of the form on the screen.
- The Load method of
a form appears in the code window when you double-click anywhere on the interface
of the form. Any code typed into the form's Load method executes as soon
as the form is loaded. The default form of your project loads as soon as
you (or anyone else) execute your project.
Objective #2: Use Dim statements
to declare variables and understand the physical process of memory (RAM)
allocation.
- You should get used to declaring all variables in
a program with Dim statements. Declaration
statements are used to declare variables. A variable should be
declared one time before it is used later in the program. It is an error
to declare a variable twice or more in a program. Declaring a variable
associates a variable name with an area of memory (i.e. RAM) so that the
variable can store a value (numeric or string). Declaring a variable also
specifies a certain data type for the variable which determines how many
bytes of memory are reserved to store the variable's value. For example,
Dim dblPrice As Double = 0.0
causes 8 bytes of memory to be reserved to store the
value of the variable dblPrice.
Furthermore, VB automatically initializes the Double variable
to the value 0.0. While the ...= 0.0 part
of the declaration statement above is optional, it is always a good idea
to initialize a variable to a number such as 0 when it is declared. In some
computer languages such as C++, variables are not automatically initialized
to zero when they are declared. Double variables
should usually be initialized to 0.0 while Integer variables
should usually be initialized to 0 as in
Dim intNum As Integer = 0
- Dim is an abbreviation
for "dimension". In old-fashioned versions of BASIC programming
language, to dimension a variable meant to make room for the variable in
the computer's memory.
Objective #3: Understand each of the basic
data types used by Visual Basic.
- You must carefully choose the data type for
each variable that you declare in your program.You must use a data type
that can store numbers that are in the range of values that you expect
the variable to possibly hold during a program's execution. Try not to
choose data types that are way too large or you will be guilty of wasting
memory space.
- For example, if you needed to store the number of hamburgers
sold at a McDonald's restaurant in one day, you should probably use a variable
with the Integer data type to allow for
a maximum number of 2147483647 hamburgers sold and since hamburgers are
sold by the whole unit and Integer variables
are meant to store whole numbers. However, if you needed to store the number
of hamburgers sold
by
ALL
of
the McDonalds
restaurants
in
the U.S. throughout history, it would probably be necessary to use a variable
with the Double data
type to allow for 3 billion or more hamburgers since the signs at McDonalds
now claim to have served "billions".
|
data type |
prefix |
characteristics |
range |
size (bytes) |
|
|
|
|
|
| Boolean |
bln |
True or False |
True or False |
2 |
| Byte |
byt |
a single character (letter, symbols, or digit)
from the Unicode chart |
0 to 255 |
1 |
| Char |
chr |
a single character from the Unicode set |
0 to 65535 |
2 |
| Integer |
int |
whole numbers only |
-2,147,483,648 to 2,147,483,647 |
4 |
| Long |
lng |
whole numbers only |
-9,223,372,036,854,775,808
to -9,223,372,036,854,775,807 |
8 |
| Single |
sgl |
decimal numbers |
-3.402823E38 to -1.401298E-45
for negative values; 1.401298E-45 to 3.402823E38 for positive values |
4 |
| Double |
dbl |
large, decimal numbers |
-1.79769313486231E308 to
-4.94065645841247E-324 for negative values; 4.94065645841247E-324
to 1.79769313486232E308 for positive values |
8 |
| Decimal |
dcm |
better precision to store decimal values
than Single or Double |
+/-79,228,162,514,264,337,593,543,950,335
with no decimal point; +/-7.9228162514264337593543950335 with 28
places to right of decimal; smallest nonzero number is +/-0.0000000000000000000000000001 |
8 |
| Date |
dtm |
store dates |
January 1, 0001 to December 31, 9999 |
8 |
| String |
str |
text, symbols, digits |
0 to about 2 billion Unicode
characters |
10 + (2 * string length) |
| Object |
obj |
any type can be stored |
n/a |
4 |
| Collection |
col |
groups of objects are stored in Collections |
|
|
| User-Defined Type |
udt |
we will not be studying user-defined types |
|
|
(We will not be using some of the data types mentioned
in this chart until later in the course.)
- It is dangerous to mix data types in Visual Basic
as in the assignment statement,
dblTotal = intApplesPrice + dblCandyPrice
since an Integer and
a Double are
being added in what is called mixed-mode addition. Realize that you are
asking VB to add a 4-byte variable to an 8-byte variable! That is sort
of like mixing apples and oranges. If the expression is being stored to
an Integer variable, such as:
intTotal = intApplesPrice + dblCandyPrice
the result will be rounded! If the expression is being
stored to a Double variable
as in
dblTotal = intApplesPrice + dblCandyPrice
the result will have the expected decimal digits.
Note that you can't always assume that a computer programming language allows
you to mix data types within expressions. In some other languages, truncation will
occur causing the decimal portion of a computed number to be lost.
- The reason why an Integer can
only store a whole number as high as 2147483647 is because of the fact that
an Integer is 4 bytes in size. Since 4 bytes is equivalent to 32 bits, the
largest binary value that can be stored in an Integer variable
is 1111
1111 1111 1111 1111 1111 1111 1111. However, the leading (leftmost) bit (known
as the sign bit) is used to keep track of whether the value is positive
or negative, so only 31 bits are used to store the variable's actual value.
Since 2^31 is 2147483647, you may think that 2147483647 should be possible
as an Integer value. But since the value 0 must be a possible value, 2147483647
(which is 2^31 - 1) is the largest value that can be stored in an Integer variable.
On the other hand, -21474836478 is the least (most negative) value that can
be stored in an Integer.
- If you try to add one or more to an Integer variable that
has the value 2147483647, an overflow error occurs
since the maximum value. Variables of the Double data
type overflow at a point much higher than Integer's.
- The Unicode chart (formerly called the ASCII
chart - pronounced "ask-key")
is a list of letters and symbols along with their corresponding numeric values
that the international community has agreed upon. Every letter and symbol
of every language has been given a range of numbers between 0 and roughly
65000. The lowercase English alphabet goes from a which is 97 to z which
is 122. The uppercase alphabet goes from A which is 65 to Z which is 90.
In this VB programming course, you are required to memorize uppercase A which
is 65, lowercase a which is 97, and blank space which is 32. From those values,
you can derive the other consecutive values and you can determine wether
one word or phrase is "alphabetically less than or greater than" another
word or phrase.
Objective #4: Name variables using the InterCap
method and the appropriate data type prefixes.
- Use sensible and meaningful variable names that make sense.
Do not use single letters as variable names like x or y. A program that uses
meaningful, descriptive variable names is called self-documenting. This is
done so that others (teachers, coworkers, and even yourself) can understand
your program easier.
- Variable names along with names of methods are also considered
to be identifiers.
- It is conventional though not required by the VB compiler
software that you begin a variable with a prefix that identifies its data
type. See the chart above for the standard prefixes. So a good variable name
might be intRuns to store the number of
runs scored in a baseball game program. However, you may use multiple words
to more fully describe the variable's purpose. A better variable name might
be intRunsScored. Each word in the variable
name (besides the prefix) should be capitalized. This method of capitalizing
the words in an identifier is known as the InterCap method of naming variables.
- In most programming languages, including VB, an identifier
must begin with a letter and not a digit or a symbol. Thus the variable names 2Many or %More would
not be valid. Technically, the variable name int2Many would
be valid since an identifier can include digits as long as a letter is the
first character. You cannot include a space within an identifier either.
Therefore the variable name intRuns Scored would
not be valid. To be safe, you should not use more than 31 characters in an
identifier either.
- Examples of good variable names: intNumStudents,
dblTotalPrice, dblSalary, strFirstName
Objective #5: Use assignment
statements to calculate and store mathematical results and to change the
properties of objects.
- An assignment statement is a statement
that is used to store a value into a variable or object's property. An
assignment statement typically includes an assignment operator which is
the equals symbol.
- Assignment statements evaluate the mathematical expression
on the right-hand side of the assignment operator and assigns the resulting
value into the variable on the left-hand side of the
assignment
operator.
- For example, the statement
intNum = 5
is an assignment statement that stores the value
5 into the variable named intNum.
Instead of a simple numerical value like 5, a mathematical expression can
be typed on the right side of the equals symbol as in
dblAnswer = intNum * 1.99 + intNum * 1.99 * 0.06
where the righthand side of the equals symbol must
be simplified first before the final result is assigned to the variable dblAnswer.
Never type an assignment statement with a mathematical expression on the
left of the equals symbol ( e.g. intNum
+ 5 = intAnswer ) since it causes a compile
error.
An assignment statement can also store a string value (which is a word or
phrase) into a String variable
or an object's property such as
strName = "Minich"
or
lblAnswer.Text = strFirstName + " " + strLastName
Notice that the + symbol is working as a concatenation operator rather
than an addition operator in the example above. (Visual Basic also
allows the & to be used as a concatenation operator.)
When you declare Integer and
Double variables it is good style to initialize
them to zero as in
Dim dblAmount As Double = 0.0 or Dim
intNum As Integer = 0
but you cannot initialize a String variable
to zero since you can't store numbers in String variables.
Therefore, it is safe to initialize a String variable
to the empty string (aka null string).
The empty string is a string with no characters and is represented as two
double quote symbols typed next
to each other with no space in between as in "". Here is a declaration statement
that initializes a String variable to the empty
string
Dim strName As String = ""
You can also assign the empty string to a String variable
or the Text property of a textbox or label
at anytime during a program. Examples:
strName = ""
lblWinner.Text =""
- Examples:
dblRate = 0.035
dblInterest = dblPrincipal * dblRate * intTime
strName = "John Doe"
REMEMBER, DO NOT CODE
THE FOLLOWING: x
+ 8 = y which
is "backwards" as an assignment statement.
- You must be careful distinguish between string data
and numeric data (which includes Integer, Long, Single, & Double).
For example, the string "13" is not equivalent to the numeric
value, 13, that may be stored in a variable of the Integer data
type. The double quotations are used to show that the string "13" cannot
be added, subtracted, etc. from another numeric variable. The quotations
acts as delimiters showing precisely where the string begins and ends.
The string "13" is
different from the strings " 13" and "13 " which
have spaces before and after the 13.
- With the Val function,
one could change "13" into 13 as in
intNum = Val("13")
- The CInt function can also be used to change "13" into 13 as
in
intNum = CInt("13")
- The Str function can be used to change the numerical value 19610 into
the string "19610" as
in
strZipCode = Str(19610)
- The ToString method can also be used to change a numeric variable into a
string. The statement
Dim intNum As Integer = 19610
Dim strZipCode As String = "00000"
strZipCode =
intNum.ToString()
causes the string "19610" to be stored in strZipCode.
Notice the required empty parentheses after the ToString method.
- If a statement is cut-off along the right edge of
the paper when a program is printed out, it is necessary to break up the
statement so that it appears over two lines of code. This can be done by
typing the line continuation operator ( _ ) after a space anywhere next
to an operator. The continued second line of code should be indented for
good style. For example, rather than
dblPrice = dblPRICE_PER_BOOK * intNumBooks + dblPRICE_PER_BOOK
* intNumBook * PA_SALES_TAX_RATE
you could type out
dblPrice = dblPRICE_PER_BOOK * intNumBooks
+ dblPRICE_PER_BOOK * _
intNumBook * PA_SALES_TAX_RATE
- Besides being used for mathematical purposes, assignment
statements can be used to change the value of an object's property. The statement
lblMessage.Text = "Hello World"
causes whatever was stored in the Text property
of lblMessage to be overwritten with the
string "Hello World". You can
even make an object disappear by using the Visible property
in the following statement
lblMessage.Visible = False
The Visible property is
used to make an object or invisible depending on certain conditions during
a program's execution. Even though a textbox with a Text Property, "You
have won the game.", may be present on a form, it may be made invisible
for the duration of a game. Then, only if the user actually wins the game,
would the Visible Property be changed to True in
order for the user to know that he or she won the game.
- So let's say that you want to write a computer program that computes your grade for a class at school. You could use variables and one button. First you must be able to compute your grade by hand with a calculator or scratch paper. How can you train a computer to compute your grade if you do not know how to perform the algorithm yourself? So you add up the points earned on all of your homeworks and tests and divide by the sum of the points possible for those assignments. This gives you your grade percentage. Okay, so how many numbers do you end up scribbling onto your scratch paper as partial subtotals or intermediate calculations? Probably three. You added up the points earned as one subtotal. You added up the points possible as another subtotal. And, the quotient that you calculated by dividing those two numbers was a third important number that you wrote down. Well, what would be three good, descriptive variable names for those three values and are they whole numbers or decimal numbers? The variable names intPointsEarned and intPointsPossible would be good names for the first two and there data type should be Integer since they would always be whole numbers. Do not use short variable names like x and y or even intPE and intPP since you probably wouldn't remember what those cryptic names mean if you needed to update your program a few years later. In fact, ask your math teacher sometime why you've been using x and y as varaible names in math class all of these years. Those problems don't seem to relate to the real world like computer programs where every program has meaning and variable names that explain the purpose of a given program. The other variable could be named dblGradeAverage and it should be a Double rather than an Integer since it is likely to store decimal numbers. Next you need to declare these variables with declaration statements and initialize them to the appropriate values.
Dim intPointsEarned As Integer = 90
Dim intPointsPossible As Integer = 100
Dim dblGradeAverage As Double = 0.0
Then you write one or more assignment statements to perform the calculation
dblGradeAverage = intPointsEarned / intPointsPossible
Finally you decide that you want to display the answer in a message box with the statement
MessageBox.Show(dblGradeAverage)
All of this code could be typed into the Click method of a button. Can you describe any improvements to the user interface, user-friendliness, functionality,
or efficiency of this program?
- It is usually possible to accomplish the same task by using no local
variables that you could accomplish with several variables. For example,
the following two code segments produce the same results
Short Version
lblAve.Text = Str((Val(txtScore1.Text) + _
Val(txtScore2.Text)
+ Val(txtScore3.Text)) / 3)
Long Version
Dim intTest1 As Integer = 0 ' student's 1st
test score
Dim intTest2 As Integer = 0 ' student's 2nd
test score
Dim intTest3 As Integer = 0 ' student's 3rd
test score
Dim dblAverage As Double = 0.0 ' student's average
test score
intTest1 = Val(txtScore1.Text)
intTest2 = Val(txtScore2.Text)
intTest3 = Val(txtScore3.Text)
intSum = intText1 + intTest2 + intTest3
dblAverage = intSum / 3.0
lblAve.Text = Str(dblAverage)
There are a number of differences between the two code segments besides the
obvious difference in length. The short version does not use any variables.
Instead, it computes the results by directly working with the textboxes and
label. This does save some memory since no variables are declared but using
variables makes it easier to maintain and upgrade a program. The use of variables
in the long version gives the programmer the opportunity to document and explain
each of the variables and this makes the program easier for other programmers
to understand. For example, in the long version, it is not understood that
it is a student's test scores that are being averaged. The long version is
nicely spaced out as well making the code easier to read and analyze.
- If you attempt to store a decimal number in an Integer variable, Visual
Basic will round the value first. For example, the statement
Dim intWhole As Integer = 3.6
results in the number 4 being stored in the variable intWhole, not 3.6. However,
due to the type of rounding used in Visual Basic if the number is 2.5, the
value 2 would be stored in intWhole since 2 is an even number. If the number
is 3.5, the value 4 would be stored. This type of rounding is called "Banker's
Rounding". Search Google or see this
link for more information.
Objective #6: Use the order of operations to
evaluate expressions and to write proper expressions.
- Expressions are groups of operators and operands that
can be evaluated.
- Examples of expressions:
9 + intNum - 12
(intGame1 + intGame2 + intGame3) / 3
- Operators
- unary operators
- is the negative sign
- binary operators
^ is
the exponent operator in VB (for example, 2 ^ 3 evaluates
to 8 since 2 to the third power is 8). Since few other computer
languages allow the ^ to be used as the exponent operator,
later in this course, you will learn how to use the Pow method
from the Math class to perform
exponentiation.
* is
the multiplication operator
/ is
the division operator
Mod is
the modulus operator. The modulus operator finds the remainder
of a division problem. For example, 10
Mod 3 evaluates to
1 since the remainder of 10 divided by 3 is 1. Other examples
are 12 Mod 5 is 2, 4
Mod 3 is 1, 4 Mod 2 is 0, 10
Mod 10 is 0.
+ is
the addition operator
- is
the subtraction operator
- Operands are the numbers or variables
that are bound by the operators.
- In the expression x
+ 3 both
x and 3 are operands.
- Mathematical notation must be written in lines of code.
For example, in computer programming, you must represent the fraction one
half as 1/2 rather than writing it with a fraction bar as you would in a
mathematics
classroom.
- Insert parentheses where necessary in order to preserve
the correct evaluation. That is, you must realize that VB obeys the order
of operations which some students learn as "Please Excuse My Dear Aunt Sally" .
The rule-of-thumb is to add extra parenthesis when you are in doubt if they
are required or not.
But
note,
though, that
later
in
the school year, your teacher may deduct points for unnecessary parentheses
in your code. Also note that multiplication and division are actually tie
and should be evaluated from left to right in the order that they appear.
The
expression 12 / 3 * 4 evaluates to 16 and
not 1. The same goes with addition
and substraction. The expression 4 - 2 + 2 evaluates
to 4 and not 0. The Mod operation fits in between multiplication/division
and addition/subtraction. The expression 10 Mod
4 * 2 evaluates to 2 since
the multiplication is performed first before the modulus.
More examples:
- 10 / 5 * 2 evaluates to 4 (not
1)
- 24 /
8 * 4 evaluates to 12 (not 0.75)
- 20 /
2 * 5 evaluates to 50 (not 2)
- 2 *
2 * 2 / 2 * 2 evaluates to 8 (not 2)
- TRY THIS
ONE: 36
/ 18 * 2 evaluates to ?
- 10 - 5 + 5 evaluates to
10 (not 0)
- 100 - 3 + 97 evaluates to
194 (not 0)
- 50 + 60 - 3 + 100 evaluates
to 207 (not 7)
- TRY
THIS ONE: 100
- 5 + 5 - 5 + 5 evaluates to ?
- Note that VB computes the two examples below differently
behind-the-scenes, even though the final answer may be the same in both
cases:
dblFahr = 9 * dblCel / 5 + 32
dblFahr = 9 / 5 * dblCel + 32
Objective #7: Know how to set break points,
examine values of variables and expressions in the Watch window, and single-step
through programs.
- A break point is a spot in a program
where you would like the compiler software to stop when it executes the program.
Simply click the gray gutter the runs along the left of the code window at
the line of code where you want to set the break point. When you execute
the program use the Debug/Start menu command rather than the Debug/Start
Without Debugging menu command.
- Visual Basic will stop executing the code at that line
and allow you to view the values stored in variables and objects' properties
in the Autos, Local, or Watch window that appears in the lower-left corner
of the screen. Right-click the Values column and uncheck "Hexadecimal Display"
if the values don't look correct.
- To single-step through the program once you have stopped
its execution at a break point, click the Debug/Step Into menu command.
You can continue to check the values of variable in the Autos window.
Objective #8: Properly design the user interface
using objects' TabIndex properties, the SetFocus method, and the focus along
with keyboard shortcuts and Clear buttons.
- The TabIndex Property is
used to give the user a more user-friendly experience while executing the
program. By setting an object's TabIndex Property
to 0, a programmer can ensure that the user can immediately enter information
into that object (usually a textbox or label). For example, a programmer
may want to set the TabIndex property of
a button to 0 to highlight that button to allow the user to simply press
the Enter key to continue with the execution of a program.
- Objects such as buttons and textboxes have the property
called TabIndex. As you create objects and
place them on the form, these objects' TabIndex properties
are set to the numbers 0, 1, 2, etc. Only one object can have a given a TabIndex property
setting of 0, only one object can have a setting of 1, etc. Whichever object
has the lowest TabIndex property will first
have the focus. By setting a form's objects sequential TabIndex properties
(say, from 0 to 7), the programmer can lead the user in a sensible, logical
manner during the program execution.
- The focus refers to the object which is selected
at any given moment during a program's execution. For example, if the cursor
is blinking within a text box, allowing the user to input a number there
by typing on the keyboard, that text box is said to have the focus. However,
if the user presses the Tab key on the keyboard, then the focus will jump
to the object that has the next greatest TabIndex property. Once the user
moves the focus to the object with the greatest TabIndex property,
pressing the Tab key will cause the focus to return to the original object
with the smallest TabIndex property setting
(usually 0, not 1).
- You should carefully create objects and place them on
a form in the order that you wish the user to be able to access them via
the Tab key. In that way, you will not have to manually set the TabIndex properties.
- An ampersand symbol ( & ) is often used before a letter
in the Text property so that the letter
is underlined. This letter's key can be typed along with the Alt key as an
alternate way for the user to activate the object's Click event.
For example, if the button is an Exit button, it is standard to underline
the
x in the "Exit" Text property.
This key combination is called a keyboard shortcut. Some
people are handicapped or have little dexterity with a mouse and prefer to
type keyboard keys. It
is the programmer's responsibility
to allow for multiple modes of input. This is called accessibility.
Furthermore, you should follow standard Windows conventions when choosing
which letter
to
set as
an object's
keyboard
shortcut such as the 'x' in Exit.
- You should place a Clear button as well as an Exit
button when appropriate for a more user-friendly, conventional interface.
A Clear button can use the textbox Clear method
to clear any textboxes on the form as in txtUserName.Clear()
- The SetFocus method
can be used to purposefully place the focus on a certain object. For example,
if you wish the focus to be placed on the Exit button at a particular point
in a program's execution so that the user only has to press the Enter key
to exit the program, you would use the statement,
btnExit.SetFocus
- One button on a form should have its Default property set
to True. This button will appear shadowed and it's Click event
will respond if the user presses the Enter key. You should also set the Cancel property to True for one button on the form. An obvious candidate for
this setting would be a btnClear or even
a btnExit button. This button's Click event
will execute if the user presses the Escape (Esc) key in the upper left corner
of any keyboard.
Objective #9: Determine the scope of a variable.
- A variable's scope determines where a variable can be used in a program.
We will study 2 levels of variable scope, local and module.
- If a variable is declared with a Dim statement
in a method, then the variable can only be used within that method. It is considered to be a local variable in that case since it
is NOT visible to any other method and cannot be used by any other
method. We say that local variables have scope that
is more narrow than module
variables.
- On the other hand, if a variable is declared with
a Dim statement at the top of a form
(i.e. class) outside of the methods in the form, then it can be used in any method
in the form. In this case, the variable is considered to be
a module variable and it has module
scope. Module variables should be named with an m prefix
so that other programmers can easily identify them as module variables.
Module variables have a scope that is considered to be wider
than local variables.
- Unfortunately, local variables lose their
values and "disappear" after a method ends. That is,
as soon as Visual Basic executes the End
Sub statement,
all local variables that are declared and used within that method
are erased from the memory of the computer.
- You should try to avoid using too many module variables
in a program. They can
make it very difficult to find logic errors. They sometimes get changed
accidentally and affect other methods. Also, fellow programmers will
find it difficult to read your programs if you use many module
variables.
- Local variables are considered to be safer than
module variables because they cannot be "corrupted" other
methods. By nature, a local variable disappears when a method
ends and cannot affect other methods. It is safest therefore
to keep the scope of your variables as narrow as possible.
- When a variable is declared
a few bytes of computer memory is reserved to store its value. When
a method ends, the memory that was used to store the value of a local variable
is no longer reserved for that variable. Eventually, another variable that is
declared later in the program may use the same exact of memory address.
Module variables have a lifetime that is longer than local
variables since their memory is reserved until the form is unloaded. Programmers
should limit the lifetime of variables as much as possible in order to
use memory efficiently. Using too much memory will slow down your program
and sometimes crashes the program or computer.
Objective #10: Add graphics to a form.
- A PictureBox object
can be used to display a graphic. The prefix pic is
used for PictureBox objects.
- You can click the browse button that appears in the Image property
of a PictureBox to make a graphic appear
in the PictureBox.
- Most types of graphics can be used with PictureBoxes including
gif, jpg, and bmp.
- The SizeMode property
of a PictureBox can be changed to StretchImage to
allow you to resize the graphic.
- Any graphics that you use within a VB project should be
stored in a folder named images that is in turn a subfolder inside of the
project's folder.
- To load a new image into a PictureBox at
runtime, use the statement
picGraphic.Image = Image.FromFile(Application.StartupPath
+ "..\images\file.jpg")
where the graphic file file.jpg is stored in a folder named images that in turn is found
in your project folder. You can use this simpler version if file.jpg is found in your bin folder
picGraphic.Image = Image.FromFile(Application.StartupPath
+ "file.jpg")
To clear an image from a picture box, use the statement
picGraphic.Image = Nothing
- Note that System.AppDomain.CurrentDomain.BaseDirectory() may be used instead of Application.StartupPath in the examples above.
- Another way to change the graphic displayed in a PictureBox is with
picGraphic.Image = New Bitmap(Application.StartupPath + "..\images\file.jpg")
- You can also draw an object to a buffer area using the form's CreateGraphics method. Here's an example:
Dim objGraphics As Graphics
objgraphics = Me.CreateGraphics
objgraphics.Clear(system.Drawing.SystemColors.Control)
objgraphics.DrawLine(system.Drawing.Pens.Chartreuse, 0, 0, _
Me.DisplayRectangle.Width, Me.DisplayRectangle.Height)
objgraphics.Dispose()
See this reference http://www.samspublishing.com/articles/article.asp?p=25723&seqNum=5&rl=1
Objective #11: Use the computer graphics
coordinate system.
- The default window coordinates do not work similarly as
the typical mathematics graph. In Visual Basic's coordinate system (and most
programming graphics environments) the y-values range from 0 to 300 as you
follow down the screen from the upper-left corner. The x-values range
from 0 to roughly 300 as you follow across the screen from left to right.
- The width and height of the default size of a form are
roughly 300 pixels. It is not recommended at this point in our course, to
resize your form.
Objective #12: Use color with objects.
- Using predefined constants in the Color class
you can assign colors various objects. This allows you to use a multitude
of colors including the VB color constants such as Color.Red,
Color.Blue, and even Color.HotPink. For example, you can set the background
color of the form to hot pink using the statement
Form1.BackColor = Color.HotPink
- You can also use the FromArgb method
to assign colors. For example, you can set the background of a form to
an interesting color with the statement
Form1.BackColor = Color.FromArgb(45,
152, 99)
- The FromArgb method takes
3 parameters. All three parameters must be integers in the range 0 to 255.
The first parameter refers to the amount of red, the second refers to the
amount of green and the third refers to the amount of blue. For example,
to make the color blue, you would use the values 0, 0, 255 meaning that the
resulting color has 0 parts red, 0 parts green, and 255 parts blue.
- To create the color black use 0, 0, 0.
To create the color white, use the function 255, 255, 255.
Objective #13: Use the DrawLine, DrawEllipse &
other Graphics class
methods.
- You can draw lines directly on the form using the DrawLine method
from the Graphics class.
- You can use the DrawLine method like this
e.Graphics.DrawLine(Pens.Black, 10, 20, 30, 40)
In this example, a black line with a thickness of one pixel will be drawn from the starting point (10, 20) to the end point (30, 40). That is, 10 is the x-coordinate of the one endpoint and 20
is the y-coordinate of that endpoint. Thirty would be the x-coordinate of the other
endpoint and 40 would be that endpoint's y-coordinate.
- A rectangle or square can be created using the DrawRectangle method. For example, the statement
e.Graphics.DrawEllipse(Pens.Black, 50, 50, 100, 200)
would draw a black circle that is bounded by a rectangle with a top-left corner at 50, 50 and a width of 100 pixels and a height of 200 pixels.
- An oval or circle can be created using the DrawEllipse method.
For example, the statement
e.Graphics.DrawEllipse(Pens.Black, 50, 50, 100,
200)
would draw a black circle that is bounded by a rectangle with a top-left
corner at 50, 50 and a width of 100 pixels and a height of 200 pixels.
- The DrawLine, DrawRectangle, and DrawEllipse methods
are typically
placed in the form's Paint method as
in
Private Sub Form1_Paint(...)
Handles MyBase.Paint
e.Graphics.DrawLine(New Pen(Color.Black, 2), 10, 20, 30, 40)
End Sub
- There are many other drawing methods that come from the
Graphics class .
You can learn how to use them by browsing
the VB API. An API is a list of classes and methods in a
programming language. An API is meant to be used as a reference to professional
programmers. Click
the menu command View/Object Browser and then click
the
plus symbol next
to System.Drawing
and the next
System.Drawing
entry.
Highlight
the Graphics class and browse through the
window pane on the right to see other
interesting
drawing
methods
that could be used in the example above. For example, you can draw a string
(i.e. print a word) on the form using the DrawString method as in
e.Graphics.DrawString("Hello", New Font("Arial", 12), Brushes.Black,
30, 40)
where the word "Hello" will be printed in Arial font size 12 with the upper-left coordinate of 30, 40.
- Draw a polygon from a set of points as in this example
Dim points() As Point = {New Point(10, 20), New Point(30, 30), New Point(50, 10), New Point(30, 10), New Point(50, 30)}
e.Graphics.DrawPolygon(Pens.Black, pts)
The statement
e.Graphics.SmoothingMode = Drawing2D.SmoothingMode.AntiAlias
can be used to make it a smoother line.
- Draw a path as in this example
Dim path As New GraphicsPath
path.AddLine(10, 40, 60, 40)
path.AddEllipse(60, 30, 30, 20)
e.Graphics.DrawPath(Pens.Red, path)
- Draw a pie slice as in this example
e.Graphics.DrawPie(Pens.Green, New Rectangle(10, 70, 40, 30), 10, 45)
- Draw an arc as in this example
e.Graphics.DrawArc(Pens.Green, New Rectangle(60, 70, 40, 30), 10, 45)
- Draw a closed curve as in this example
Dim points() As Point = {New Point(150, 150), New Point(200, 200), New Point(180, 150), New Point(130, 200)}
e.Graphics.DrawClosedCurve(Pens.Blue, pts)
Draw an open curve by using DrawCurve instead of DrawClosedCurve
- Drawa Bezier curve as in this example
Dim ptfs() As PointF = {New PointF(150, 25), New PointF(185, 10), New PointF(200, 50), New PointF(160, 30)}
e.Graphics.DrawLines(Pens.Black, ptfs)
For Each ptfs As PointF In ptfs
Dim rect As New Rectangle(CInt(ptf.X - 2, CInt(ptf.Y - 2), 4, 4)
e.Graphics.DrawRectangle(Pens.Blank, rect)
Next pft
e.Graphics.DrawBezier(Pens.Black, ptfs(0), ptfs(1), ptfs(2), ptfs(3))
or use this statement in place of the last one above
e.Graphics.DrawBeziers(Pens.Orange, ptfs)
- The command Me.Refresh() can be used to call the Paint method. Me.Update() may also work.
Objective #14: Use a call statement to execute
a method from another method.
- So far in our study of VB, methods only execute in response
to the user performing an event such as clicking the mouse, which executes
an
object's
Click method, or starting the project, which
executes the startup form's Load method.
- However, it is possible to execute a method with a statement in another
method.
For example, if you have a button that calculates the sum of the
values stored in two textboxes such as
Private Sub btnCalculate_Click(ByVal sender As
System.Object, _
ByVal e As System.EventArgs) Handles btnCalculate.Click
MessageBox.Show(Val(txtNum1.Text) + Val(txtNum2.Text))
Call btnClear_Click(sender, e)
End Sub
and if you have a Clear button that clears the entries of two textboxes such
as
Private Sub btnClear_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs)
Handles btnClear.Click
txtNum1.Clear()
txtNum2.Clear()
End Sub
you can use the statement Call
btnClear_Click(sender, e) to
the btnCalculate_Click method
so that it automatically clears out the entries when the user calculates the
sum. This statement is
a call statement and
it causes VB to execute the btnClear_Click method
without the user having to click the Clear button! Having the ability to call
methods from other methods
in this way makes code more reusable.
In this example, it is necessary to pass sender and e as parameters from the
one
method to the other method. We will learn more about parameters later in the
course. The word Call is
optional in a call statement,
so the call statement
above could have been typed as btnClear_Click(sender,
e)
Objective #15: Create
your own method that is not tied to an event.
- You can create a method from scratch so that it can be
called over and over again from other methods. This increases the reusability
and efficiency of a class and its methods.
- To create a method you make up a name for the method and type statements
into the body of the method. Here is an example:
Private Sub MoveRight()
picPlayer.Left = picPlayer.Left + 20
picPlayer.Visible = (picPlayer.Visible + 1) Mod 2
End Sub
The first line of code is called the method header. MoveRight is the name of the method. The name of the method, MoveRight in this case, can be anything the programmer desires. However, you should use logical names for methods that indicate their purpose. You should also use the InterCap method of capitalizing each word in the name of the method. No prefix is required though for a method's name. The parentheses
are empty since it requires no
parameters
to
be passed
to
it.
There are two
indented statements in the body of the method above. At this point in our
VB course, methods should be declared as Private rather
than Public so
the first word in the method header should be Private.
The first body statement causes the picture
box picPlayer to
move right each time the method is called. The second body statement makes
the picture box
invisible on every other click. It is not critical at this point in
our VB course that you understand how this statement works. But, if you
are curious, see Mr. Minich.
- To call the MoveRight method
illustrated above from within another method such as a button's click method
you can use either of the following call
statements:
Call MoveRight()
MoveRight()
- Another example of a method made from scratch is:
Private Sub ChangeColor()
Me.BackColor = Color.Red
End Sub
This method would change the background color of the form to the color red.
- You can pass a parameter to a method
to make it even more flexible. A parameter is like a variable. It has an
associated data type (usually Integer or Double)
and the word ByVal must
be typed in front of it. In the following example, dblPrice is
a parameter.
Private Sub DisplayPriceWithTax(ByVal dblPrice
As Double)
Dim dblTotalPrice As Double = 0.0
dblTotalPrice = dblPrice + dblPrice * 0.06
MessageBox.Show(dblTotalPrice)
End Sub
The following statement could be used to call the method DisplayPriceWithTax:
Call DisplayPriceWithTax(10.00)
A message box with the number 11.20 will be displayed
since 6% tax added to an item that costs $10 is $11.20
Objective #16: Understand the concept of reusability
- One motto in all computer science courses is "Reuse, Reuse, Reuse." This means that programmers should write methods, functions, forms, etc. and then be able to reuse those items in other programs and projects without having to change or modify them. For example, if you create a function with code that computes the Pennsylvania sales tax on a user-inputted value for one program, you could use it for the rest of your programming career.
- Programmers must always be thinking about reusability as they design programs and algorithms. As you gain experience, you will learn what kinds of tasks can be solved with methods and functions that may apply to future programming assignments. You also will learn how to separate the code that does not change from the the code that will have to change for future assignments. In that way, during pseudocoding, you will be able to organize the algorithm and your efforts so that you can eventually reuse certain modules of code.
- There are many methods and controls at vbcode.com and other Web sites that you can use for free or purchase. This saves a lot of time and effort.
- Reusing code also saves time during program testing. If you had already thoroughly tested certain methods, you will not need to test that part of a program in the future. Also, reusing code makes programs more consistent with one another and therefore more user-friendly.
Objective #17: Use Flash swf files in a VB project.
- In order to use a Flash movie in a VB program, you must first create the Flash movie itself. Publish the movie as a swf file and store that file in your VB project folder.
- Add a reference to the COM SWF ActiveX control. Right-click on the tool box. Select “Add/Remove Items…”. Select “COM Components”.
Select “Shockwave Flash Object”. Click OK. If necessary, find Flash9.ocx on the Internet and place a copy of this file in your Windows/System32/Macromed/Flash folder.
- Now that a SWF control is in your toolbox, place a SWF object on your form and name it something like FlashObj.
- In the Properties window, type the path to the actual swf file in the Movie URL property.
- Use the following code to play a Flash object reference named FlashObj
FlashObj.Movie() = Application.StartupPath & "example.swf"
FlashObj.Play()
Later you can stop the Flash movie animation with the command
FlashObj.Stop()
When you are finished using the Flash movie in your project, you should clear it out of the memory with
FlashObj.Dispose()