Visual Basic 1
Index of project examples in this
My CSCI 110 powerpoints will have an index
of the VB examples generally as the 2nd
slide. For this ppt show, here is an index
of project examples
• The Two-textboxes example
• A Messagebox example
• The F to C converter
• Gaddis/Irvine text comments and chapter
1 screenshots
About the Schneider text examples
• VB 2005 Express edition can be downloaded
free from MS to install on your own machine.
• You will need the 2005 edition VB to run the
examples on the (other) text CD.
• However, my examples and the text examples
should run in the labs, which have this edition of
• As the semester progresses I will update our
labs, projects and these powerpoints to reflect
more examples from our text.
Here’s a VB form example: hourly wage
calculations. We will write this program next week.
About VB
• VB is a (sort of) object-oriented language
with a large IDE providing much developer
• Because of this, the environment is as
hard to learn as the language, or harder!
• But it won’t be hard to develop impressive
VB projects right away.
• IDE means integrated development
• An IDE provides a means of developing
and test-running software.
• The VB IDE is “part of” MS’s large .NET
software system.
• There is quite a lot of mid-size enterprise
sw development going on in VB!
VB version etc
• Labs should have the 2005 version of VB
in the programming folder.
• This large program will take a while to load
and VB programs will generally run fairly
slowly from within the IDE.
• You can download free .NET software for
your home computer from Microsoft.
To run VB: Click on the MS icon
(probably in the programming folder)
Select windows application
Select new project (windows application), then
select VB project from other types and click ok.
Note: You can give a project a special name by typing
something else where it says name when you select New
Project. This is a good idea, because it will get hard to
remember what’s what.
Creating a VB application in the express
edition…view toolbox selected
A button with the hot key (alt-P)
Selecting new vb project (as per above)
will open the form design interface
Selecting “View” on menu bar opens various
window “view” options. Here, “view toolbox”
was selected.
Pull down the View options on the
• Use the toolbox to select “tools” (called
“controls” in VB) for your project
• Use the properties window(s) to set
properties for your form and its control
• Use the solution explorer window to view
the different elements of your solution.
Plopping components on your form
• Either double clicking a component in the
toolbox menu, or clicking the component in
the toolbox then clicking on your form, will
put a control on your form.
• Once there, you can “select” it, resize it,
align it, or drag it to where you want it to
go, or add other properties to it like tab
order or a tooltip.
Here’s a form with a couple of
textboxes plopped on it
Some popular components
• Textboxes, buttons, and labels are the most
popular components. Textboxes hold text - often
user input.
• Labels are for labeling other components,
• Buttons can be “pressed” to fire an event.
• Picture boxes can “hold” images
• comboboxes allow multiple choices.
• Listboxes are like multi-line textboxes,
(Textboxes can also be set to be multiline).
• Radiobuttons and checkboxes display available
choices: the user can select/deselect them
More on controls
• Controls can be grouped into groupboxes
to help rationalize a complicated display.
• There are other types of controls as well –
we won’t learn how to use them all this
• You are already familiar with many
controls as a user of window applications.
Running your VB application
• At any time during development, as long
as you have no errors, you can “run” your
• To check for errors: Select build from the
menubar and then select build solution
(or rebuild)
• To run or check for errors: Select Debug
on the menu bar, and then pick start or
press F5.
Running an application with two textboxes
(there’s no functionality)
• You need to close your running
application (window) before continuing
development on it. Just click the X in the
upper right corner of the running form’s
window or, in the debug menu, select
“stop debugging”.
• It is useful to “build” or “debug” periodically
to make sure you have what you want and
what you have works.
Selecting the form and editing the text property in
the properties window allows you to change the
text displayed on the form, its “name”, when the
form comes up
More “basic” development: Let’s
add functionality to a form
• Clicking on the blank form in the development
window will cause a “code window” to pop up.
You can provide code specifying the action to be
taken when the form is clicked.
• VB, VC++ and Java are event-driven
• This means mouse-clicks or letters typed
at the keyboard may “fire” (start, initiate,
cause) events.
• When events are fired, the programmer
can specify what is supposed to happen.
• Subroutines are the Basic program language name for
programmer-specified functionality.
• They are referred to as “sub” in the VB code.
• VB helps you to write subs by providing stubs for any
event-fired subroutine.
• This saves memorizing some things. It also saves typing
and time.
• BUT: You must be careful: make sure the event sub
which is stubbed in is the one you want.
• Cutting and pasting stubbed subs can be dangerous
since some stubbed values may still need editing.
Our first vb sub
• Let’s open a little message window when
the user clicks anywhere on the form.
• In VB, messagebox is the name of the little
message window component.
• Double-clicking on the form in
development will switch us to a code
window where a sub for this event-handler
has been stubbed for us.
Form Click sub stub
• Below is the stub for form click.
• Be careful, as VB may stub in a sub for form load.
• In any case, you can edit the stub to look like this:
Private Sub Form1_Click(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles MyBase.Click
End Sub
Our sub
Private Sub Form1_Click(ByVal sender As
System.Object, ByVal e As
System.EventArgs) Handles MyBase.Click
MessageBox.Show("A message!",
"first VB example",
‘comment…bold text is what you type
End Sub
Remarks about this sub
• Fit code on one line or use the space-thenunderscore to continue a VB statement onto the next
• Important note: Most of these slides show code
spilling onto multiple lines, which won’t work.
• What you should type into the stubbed sub on one
line is:
MessageBox.Show("A message!", "first VB example",
More remarks on this subroutine
Private Sub Form1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Click
• Notice the name: Form1_Click. This is generated
automatically, and would have specified a different name
for the method if we had given our form a different name.
• In general, ComponentName_Click is the name of the
subroutine handling mouseclicks on a control component
named ComponentName.
• MyBase.Click is the event for clicking on the form.
• We’ll learn more about the parenthetical arguments and
the “Handles…” another time.
Now, run the example (remember: select
debug, then click start)
An empty form appears, but…click on it
A message box pops up
An exercise to test your understanding:
Fix your message box to look like this
Setting properties for components
• Clicking a component on your form will open its
properties window (probably on the right.)
• You can also open properties window by
selecting view>properties
• You can specify names and initial (text) values of
control components.
• You can resize labels (or textboxes) or change
the text font, for example, if the text doesn’t fit.
• You can align text in a component.
• You can set colors.
Now let’s change the form
• Add a label: Set its text property to Enter fahrenheit.
Give it a name like lblInput as its name property.
• Add a textbox: set text property to blank contents, name
property to something like txtInput
• Add another textbox: set read-only property to true (see
below) and name it, for example, txtOutput
VB Naming conventions
• Although you can name components almost
anything you like, VB conventions recommend
standard prefixes frm, lbl, btn, txt (and so on) for
form, label, button, textbox (and so on).
• I gave my label and textboxes the names:
lblPrompt, txtInput, txtOutput.
• Using standardized conventional names will help
you remember what things are and what they
are used for as your applications become more
VB component properties
• I put text in my label instructing the user what to
• I set input’s text to blank.
• I set output to be read-only (not editable).
• ‘&’ in the text property of a button defines a
hotkey for keyboard input. So, if the text on a
button is “X&YZ” then typing the letter ‘Y’ on the
keyboard is the same as clicking that button with
the mouse.
• See the next slides for setting properties.
Setting properties
• As you add components, clicking them will open the
properties window.
• In the properties window, you can give the components
names, and set other property values.
Setting properties
• Clicking “elsewhere” on your form or in
another window confirms property
• Of course, you can change properties
• Remember to save your application each
time you make changes.
Let’s look at the form (start debugger). Except for
the message box there’s still no real functionality
What else do we want?
Get rid of the pop-up message box? Your choice.
Make the form “go away” when we are done. (This is
already provided by Microsoft windows application
code when the X is clicked in the upper right of the
running application window.)
Add functionality: the famous F to C conversion from
ninth grade. Recall the formula C=5.0/9.0*(F-32) . The
parentheses and decimal points are needed.
Add a label for the answer
Add two buttons. Give them names. (VB convention
would be to name them btnCompute and btnQuit)
Exercise to test your
understanding: add some
components & set properties
• Complete Lab 1 and Lab 2 for this week
My new form: still no functionality
event-driven programming, continued
• VB makes handling events fairly easy, although
it is still pretty technical.
• As previously mentioned, double-clicking a
control component in the form-development
window brings up a code window with an empty
subroutine already stubbed in.
• You provide the specific code you want for your
• It is still up to you to make sure this is what you
really want!
More on the Visual environment
• VB and VC++ provide a lot of programmer
support, prompting you with components,
the proper code to provide, and the place
your code should go.
• When prompted (with a pop-up window)
you may ignore the suggestions and keep
typing, or make a selection and hit the
enter key to save some typing.
Back to the form
• How do we add functionality?
• In design-mode, double-clicking a
component will open a code window
where you can add the code you want for
this “event”.
• You can also open the code window from
the VIEW menu.
• Let’s add functionality to the compute
What’s involved?
1. We need to create appropriate variables
to hold necessary values.
2. We need to compute whatever
information we need.
3. We need to display the result so the user
can see it.
The IPO model
I-P-O = input-process-output
Many programs in real life and in this
class will follow the IPO model.
The user provides input, the program
processes it somehow, and then
generates output.
IPO is NOT the only model, transactions
(at an ATM for example), are not simple
Declarations and variable types
• Declaring variables is REQUIRED in almost all
programming languages.
• VB declarations must start with the reserved symbol Dim
• VB supports MANY datatypes. Decimal, single, and
double are some of the “real” datatypes.
• Textboxes and labels hold Strings. Strings contain
characters, possibly numeric in value, and are written
with quotes, as in “Hello” and “1234”
• Although, when you type into a textbox you don’t put the
quotes, you’ll need quotes on string constants in your
project’s code to distinguish them from names.
Here’s some of the code
• We’ll need variables to hold the fahrenheit and celsius
amounts. We’ll use Dim and make them Double.
(Decimal or Single data types would also work).
• The code below functions, although it contains a
potential problem which, as it happens, VB handles for
us in this case.
• What’s the problem in the 2nd line?
Dim celsius, fahr As Double
fahr = input.Text
‘fahr should be a double…is it?
celsius = (5.0 / 9.0) * (fahr - 32)
• An apostrophe begins a comment to the end of
the line
• Although it may seem silly, you should put in
comment blocks at the start of subs detailing the
variables used, the input and output variables
and parameters.
• You should comment complicated lines of code,
because you may not remember in a week (or a
year) why you did something a certain way.
An aside: Option Strict
• Setting Option Strict On (put Option Strict On
before the first line of code in your code window)
makes VB function more like C++ and Java –
that is, it won’t do automatic conversions from a
wider data type (say, String) to a narrower one
(say Double or Integer).
• This is good programming practice and will help
you avoid datatype mistakes.
• You can also set option strict on in the designer.
• When option strict is not on, VB will convert
datatypes to match expression and assignments
if it can.
An improvement
• Although VB will properly convert a string to a number (if
the string contains a number and option strict is off)
that’s not a good way to program, especially since it
doesn’t give us the flexibility of handling the exception
(that is, erroneous input & conversion thereof) ourselves.
• Parse is the name of the VB function to convert strings
into numeric values. Integers and decimals can be
parsed. We should write
fahr = Decimal.parse(input.Text)
• There are two steps being performed here: First get the
string from input, then convert it to a real number.
A complete (improved) subroutine
Private Sub btnCompute_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
Dim celsius, fahr As Double ‘my variables
fahr = Decimal.parse(input.Text) ‘get user input as a
celsius = (5.0 / 9.0) * (fahr - 32) ‘do arithmetic
output.Text = celsius.ToString("N") ‘display answer
End Sub
By the way…
• Classes Integer and Double both have parse methods to
change a String into a numeric value. You should
always use a method to do your conversions to numbers
(or back to String)
Dim snum as String =“123.45”
Dim inum as String=“6789”
Dim dub as Double
Dim intval as Integer
dub=Double.parse(snum) ‘gives the double 123.45
intval=Integer.parse(inum) ‘gives the int 6789
You can also use VB’s CStr or CDbl to convert to string (from a numeric
type) or to double (from string).
Important note
• You won’t be able to blindly copy my code
into your subroutines.
• For example, you’ll need to use YOUR
component and data variable names.
• Remember about continuing statements to
another line: You must use spaceunderscore or try to fit it onto one line.
The current form, running
Format specifiers for conversions
of numbers to strings
• VB provides format specifications:
• “N” or “n” for number, 2 decimal places given unless you
specify otherwise.
• “P” or “p” for percentage. You may optionally specify
additional decimal places.
• “D” or “d” for Integer only. You may optionally specify
• “C” or “c” for currency (dollar sign and 2 decimal places)
• Value.toString(“N0”) converts value to a string with 0
decimal places.
• Value.toString(“P3”) converts value to a string
“percentage” with three decimal places, as in “%5.678”
VB formats
• VB also provides date formatting which
(probably) we’ll discuss another time.
Now, make the form go away
• Double click your “quit” button to bring up
the code window.
• Here’s my function:
Private Sub quit_Click(ByVal sender As
System.Object, ByVal e As
System.EventArgs) Handles quit.Click
End Sub
• Me is always the name of your form, while
it is running. You can refer to components
as Me.componentName, as in, Me.input
and so on.
• Me.close() technnically just closes the
window associated with the form.
Exercise: Add More functionality
• Add a clear button which clears out all the fields
when pressed
• You might name it btnClear, put its text to
“&clear” and add the btnClear_clicked
subroutine to the code section:
Private Sub btnClear_Click(ByVal sender As System.Object, ByVal
e As System.EventArgs) Handles btnClear.Click
End Sub
Running VB apps
• You can test and run your VB from the IDE
using the debugger.
• Once completed, you can use your
application like any other program, too.
• First, you’ll have to find the .exe file
associated with your application.
• It is in the …/obj/debug directory.
In the …/obj/debug directory find
the exe file
Click the exe to run an app
Is there any more to say?
• There are lots of ways to code this F to C
• You can probably think of many things we
could do differently.
• Exercise 1: Build an application for
computing gross pay for a single
employee. Provide textboxes for payrate
and hours worked, appropriate labels, and
display gross pay.
Week 1 checklist: What should you be
able to do? Easy list
• Find the VB icon, launch VB and edit/create a VB
• Give your application a different name than the default.
• Run (in the debugger) your application at any time during
• View the toolbox.
• Add a control (or two) to your form.
• View the properties.
• Edit properties for your control like TEXT and NAME.
• Use VB conventions for naming controls.
• Open the code view.
Week 1 checklist: you should be
able to…
• Perform some simple arithmetic on values
entered and display the result.
• Recognize datatypes and declare your
variables appropriately in the proper
location of the code view.

Visual Basic - SUNY Oneonta