Lesson 2 – Forms and Decisions

Lesson 2 — Forms and Decisions
Microsoft Visual Basic
.NET, Introduction to
Programming
1
Objectives





2
Customize the look and feel of a form.
Create forms that react to user events like clicking a
button and pressing a key.
Learn to use the OpenFileDialog box.
Understand and use the various data types.
Use variables and pass information from one part of
the project to another.
Objectives





3
Use the If statement in program code to make
decisions.
Use logical expressions and relational operators.
Use GroupBoxes to arrange RadioButtons on a
form.
Use the TabIndex property to control the order in
which controls receive focus.
Import graphics to a form.
Vocabulary









4
Accelerator key
Assignment statement
Boundary condition
CInt() function
Class level
Concatenation operator
Condition
Constant
Data type









Dialog box
End statement
File filter
If statement
InputBox function
IntelliSense
InterCap
Keywords
Loads
Vocabulary





5
Pixels
Program flow
Relational operators
Run-time error
Scope





Strings
Syntax
TabIndex property
Unicode
Variable
Questions a Programmer Should Ask




6
What is the best way to present the
application?
What are the needs of the users? (What do
they need to see to do their job?)
How are the users accustomed to seeing the
information?
What colors or objects will help them best
utilize the application?
The Programming Code



Start program
Declare the variables you will use to make
calculations
Initialize values
–
–
–

7
Get the data
Process the data
Show or save the information
End program
Tip
Note the indentation of the code in the code
block. Indentation is used to make
programming code easier for you to read. It
has no significance to how Visual Basic
reads it, although many languages now
automatically indent code as you enter it. As
you go forward with this text, pay attention to
the indentation used in the Step-by-Step
exercises.
8
View Code Button in the Solution
Explorer Window
9
Tip
Visual Basic makes code easy to follow by
color-coding various parts of the code. This
helps visually organize the code and makes
debugging easier.
10
Default Anchoring
11
Tip
If you want to enter code for a different
object, use the Class Name and Method
Name list boxes at the top of the Code
window to open the object’s Code window.
12
Note
The keyword Public means that the method
has no access restrictions within this form.
The Sub keyword is an abbreviation for the
word subprocedure (block of code). Sub is
followed by the name of the control, for
example, cmdExit, an underscore (_), the
name of the current event, for example,
Click, and parentheses.
13
Creating Simple Forms





14
Start a Visual Basic Windows Application, which
creates a new Windows form.
Change the form properties (like the Text property)
as needed.
Add controls such as text boxes, labels, and buttons.
Change the properties of the controls to convey
information to the user.
Add code to the objects’ methods (event
procedures).
Pixels
Visual Studio programmers use pixels when
describing size and location information. Pixel stands
for picture element. Together your monitor and the
graphics card installed on your computer determine
the number of pixels on your screen. Typical screen
resolutions are 640 by 480 and 800 by 600. The
numbers refer to the number of columns of pixels by
the number of rows of pixels. The more columns and
rows, the higher the resolution of the picture. Higher
resolution gives more detail in a smaller area.
15
Historically Speaking
In the late 1950s and early 1960s, computer
scientists developed ways to write programs that
would interpret specialized programming languages
into machine language. These programs are known
as compilers. Before compilers, programs were
either hard-wired into the machine or the machine
was programmed directly with machine language.
With the advent of compilers, programming
languages were developed that were far easier for
humans to understand.
16
Some Things to Consider




17
What other forms will be open when this form
opens?
Will the user be able to use the other forms?
Would it be more convenient to allow the
user to see the other forms?
Should the user's attention be focused solely
on one form?
Tip
You can select multiple controls on the form
in Design mode by holding down the Ctrl key
as you click each control. Then you can
reposition all the controls at the same time.
You may also select multiple controls on the
form by selecting the Pointer tool in the
Toolbox and clicking and dragging a box
around the controls. A Step-by-Step exercise
later in this lesson explores this technique.
18
Assignment Statements
Many properties are also set by program
code while the program is running. To set an
object’s property value while code is running,
use an assignment statement. The
assignment statement as it applies to objects
and their properties has the following syntax:
object.Property = Value
19
Tip
One of the most important things programmers can
do is document their code. Internal documentation is
the easiest way of accomplishing this. Internal
documentation is called commenting. If you place
an apostrophe ( ', also called a single quote) at the
beginning of a line, Visual Basic ignores the whole
line and you can use it as a comment. As mentioned
earlier, Visual Basic color-codes the code. It displays
comments in green.
20
Windows Form Designer-Generated
Code
It appears in a neutral color with a plus symbol to the
left. Click the plus symbol to expand the entry if it is
not already expanded. Once expanded, you see
code automatically generated as you add controls to
the form and set the controls’ properties. This code
should not be altered in the Code Editor. It should
only be altered by adding new controls to the form
and by changing properties’ values in the Properties
window.
21
OpenFileDialog1
OpenFileDialog1.DefaultExt = "txt"
OpenFileDialog1.InitialDirectory = "c:\My
Documents"
OpenFileDialog1.Filter = "Text files | *.txt"
OpenFileDialog1.ShowDialog()
22
IntelliSense
As you enter a statement, a pop-up window
appears with information about the
statement’s syntax. This very useful feature is
called IntelliSense. IntelliSense will complete
words for you or just describe the structure of
the statement and the options available to
complete the statement.
23
The Open Dialog Box
24
Did You Know?
FORTRAN and COBOL were two of the first
high-level or third-generation languages
created. FORTRAN was created for use by
engineers and scientists. COBOL was
created for the business world. Updated
versions of both of these languages are still
in use today.
25
The RadioButtonCheckBox Form
26
Computer Ethics


27
Unauthorized copying of software is stealing.
It is illegal in many countries, and people and
corporations have been prosecuted for
"bootlegging" software.
Microsoft regularly shuts down illegal
auctions on Ebay.
Variables
A variable is a temporary storage location for data
used in your application. Each variable has a name
and a data type. The data type of a variable
determines what kind of value it represents. The
value of each variable, as the name implies, varies
depending on different situations. For example, you
can assign user input from a text box to a variable
and use it to do calculations. Using variables like this
also makes your code more efficient because data
stored as a variable can be processed many times
faster than data stored in the property of an object.
28
Constants
The value of a constant remains the same.
Constants are useful if you have a value that
is used over and over or if the code contains
a number that is difficult to remember, such
as the value of pi. The use of constants
makes it easier to read the code and also
maintain the code.
29
Note
When showing the syntax of a statement, items in
the square brackets are optional. Items in italics
stand for things that must be replaced with specific
instances of the item. Words not in italics and not in
square brackets are required parts of the statement.
Often, in syntax statements, two-word descriptions,
like “data type”, are combined to form a single word:
datatype. The IntelliSense help statements that
appear in the Code Editor use this style to illustrate
the syntax of statements.
30
Integer Data Type


31
4 bytes
-2,147,483,648 to 2,147,483,647
Double Data Type




32
double-precision floating-point
8 bytes
-1.79769313486231E308 to 4.94065645841247E-324 for negative values
4.94065645841247E-324 to
1.79769313486232E308 for positive values
Naming Variables and Constants
Typically, you should select a name that is
meaningful but not too long. It is helpful if you start
the variable name with a three-letter prefix that
identifies the data type; for example, str for String
data type and int for Integer data type. You cannot
include spaces in the names of your variables or
constants. Capitalize the first letter of each word in
the variable name. This naming convention is called
the InterCap method of naming variables and
constants.
33
Building Programming Skills
Before you write the code, it is helpful to write
on paper what it is you want your application
to accomplish. First, write English sentences
that describe the process of solving the
problem. Then, change the sentences into
short statements that use some of the
commands you will be using, but do not worry
about syntax.
34
Step-by-Step 2.5, Step 6
Dim strUserName As String
strUserName = InputBox("Please enter your full
name.")
Dim intAge As Integer = 21
Dim sglGPA As Single = 3.65
Dim CrLf As String = Chr(13) & Chr(10)
lblGreeting.text = "Welcome " & strUserName & "." _
& CrLf & "Your age = " & intAge _
& CrLf & "Your GPA = " & sglGPA
35
Gathering User Information Form
36
Concatenation Operator


37
&
This operator joins strings together end to
end.
Underscore Character
The underscore character is the statement
continuation character. There is no strict limit to the
length of a line of code, but it is hard to read lines
that extend beyond the edge of the screen. The
solution to the problem is to break long lines of code
into shorter lines without ending the statement. The
underscore character at the end of a line indicates
that the statement is continued on the next line. To
use the underscore character, it must be the last
character in the line and there must be a space
before the character.
38
The Scope of Variables and Constants
The scope of variables and constants
describes the lifetime of a variable and
indicates what parts of the program are
aware of each variable or constant.
39
Hint
There are many sites on the Internet that
offer free and inexpensive controls that you
can add to your Visual Basic applications.
Before creating your own controls, you may
want to see what is already available. There
is no sense in reinventing the wheel.
40
Making Decisions
If condition Then
Statements if condition is True
Else
Statements if condition is False
End If
If condition Then
Statements if condition is True
End If
41
Step-By-Step 2.6
Const AgeLimit As Integer = 12
Dim Age As Integer
Age = CInt(InputBox("Enter your age:"))
If Age <= AgeLimit Then
MessageBox.Show("Your age is under the limit!")
Else
MessageBox.Show("You are too old.")
End If
42
Note
You may want to add the Debug toolbar to your
normal toolbar display. Among many other buttons,
the Debug toolbar has two buttons to run a program:
a triangle icon to start the program with the
Debugger and an exclamation point icon that starts
the program without the debugger. The square icon
on the Debug toolbar stops program execution. To
add the Debug toolbar, right-click the toolbar area
and click Debug.
43
Important
Using an equal sign as a relational operator
is not the same as using the equal sign as
the assignment operator. Used as the
assignment operator, the value of the
expression to the right of the equal sign is
evaluated and assigned to the variable to the
left of the equal sign.
44
Group Boxes
Use group boxes to organize controls on a form. A
group box visually separates groups of related text
boxes, radio buttons, check boxes, labels, and
buttons. Radio buttons have a special relationship to
group boxes (formerly called frames) because only
one radio button of a list of radio buttons contained
in a group box can be selected. Independent groups
of radio buttons are contained in separate group
boxes.
45
Text Boxes
One important way for the user to enter data
is the text box. A text box appears on the
form as a rectangle. The user enters data
into the text box with the keyboard using all
the editing tools familiar to anyone who
works with Microsoft Windows programs.
46
Note
While double-clicking a control to add it to a
form, it is possible to add an unintended
extra copy of the control. To remove a control
from a form, select it by clicking anywhere
within the control's boundary and press the
Delete key.
47
The Annual Depreciation Form
Showing Placement of Controls
48
The AutoSize Property
The AutoSize property of the Label control
can be set by selecting its current value in
the Properties window and entering a new
value with the keyboard. Double-clicking the
name of a property sometimes toggles the
value of the property between different
possible values. In this case, the value
toggles between the two possible values of
the AutoSize property: True and False.
49
TabIndex Property
When the program is run, the control with the
TabIndex property of 0 starts with the focus. When
the user presses the Tab key, focus shifts to the
control whose TabIndex property is next in the
sequence. The value of the TabIndex property for
each control is set automatically while controls are
created. Altering the TabIndex property during the
design process lets the programmer control the
order in which controls receive focus.
50
Step-by-Step 2.7
Dim PurchasePrice As Decimal
Dim SalvageValue As Decimal
Dim Years As Integer
Dim Depreciation As Decimal
If rdbPriceOne.Checked = True Then
PurchasePrice = 2500
End If
51
Step-by-Step 2.7
If rdbPriceTwo.Checked = True Then
PurchasePrice = 4500
End If
If rdbSalvageOne.Checked = True Then
SalvageValue = 200
Else
SalvageValue = 400
End If
Years = CInt(txtYears.Text)
Depreciation = (PurchasePrice - SalvageValue) / Years
lblDepreciation.Text = Depreciation.ToString()
52
TextBox Control’s Clear Method
To clear the contents of the text box, use the
TextBox’s Clear method. This built-in method
clears the contents of the Text property of the
TextBox control, preparing the text box for
more data entered by the user. A typical
statement to clear a text box is:
txtYears.Clear(). Such a statement is usually
called from a button on the form.
53
Summary




54
Objects such as labels and text boxes are added to a form to give
instructions or information to the user or to retrieve information
from the user.
The Property window allows you to change an object's property
settings. The color, text, font type and size, and object size as
well as an object’s behavior are changed with Property settings.
Properties of objects can also be changed at run time with
program code.
Many properties use True or False settings to determine their
status at run time. These settings can also be altered later with
program code.
Program code is what actually gives instructions to the computer
to perform calculations, move objects, change properties, and
print reports. In Visual Basic, program code is typically associated
with an object and is triggered by user events.
Summary



55
The size and location of forms is set by the programmer. Pixels
are the common unit of measurement used. A pixel, or picture
element, is the smallest color dot supported by the system. The
Size property of an object is set by the Height and Width
subproperties of the object, while the Location property is set by
the X and Y subproperties.
Variables and constants must be declared before using them. A
local variable is declared by using the Dim statement. Declare
constants by using the Const statement.
Variables and constants have set lifetimes or scope. The scope
is determined by where the variable or constant is declared.
The scope of a variable is its lifetime and visibility.
Summary




56
Internal documentation is used in the program code to explain
why something was done. Internal documentation is important
for both the original programmer and the person who may have
to make alterations to the program later.
Assignment statements are program code used to assign
values to variables or properties of objects while the program is
running.
A class is a template used to create an object. Everything in
Visual Basic is created from a class.
The OpenFileDialog control is a temporary dialog box used to
get a filename from the user. Once collected, the filename can
be used to open the file.
Summary




57
Radio buttons allow the user to select from a list of options.
Only one radio button in a group may be selected. Read the
status of a RadioButton control by accessing its Checked
property.
Check boxes allow the user to select multiple items from a list
of options. Read the status of a CheckBox control by accessing
its Checked property.
The Dim (Dimension) statement declares a variable. Declaring
a variable reserves space in memory for the value of the
variable and associates a name and a data type with the
variable.
Variables are objects and, once declared, many methods are
available to manipulate the value of the variable.
Summary





58
Use the InterCap method to name variables and constants.
The If statement is used to control program flow. Statements
are executed (or not) based on the evaluation of a condition.
Group boxes are used to group controls like radio buttons
together.
Text boxes are used to collect input from the user. The text box
is a fixed part of a form, while the InputBox function shows a
temporary dialog box to collect input from the user.
A number of objects, including forms, buttons, and picture
boxes, can display graphics.