vb 2008 express for engineers
TRANSCRIPT
Introduction to Visual Basic 2008 Express
For Engineers
Introduction to Visual Basic 2008 Express Edition
The Basic programming language was developed at Dartmouth in the early 1960’s.
Visual Basic was created by Microsoft in 1991. Visual Basic 2008 Express Edition is
similar to the original Visual Basic but is much more powerful. It can be downloaded
free from Microsoft at:
http://www.microsoft.com/Express/Download/
To do any of the example labs, you will need to download and install Microsoft’s
Visual Basic 2008 Express Edition.
The Integrated Development Environment (IDE) should look something like this:
Tool Box
Solution
Explorer
Properties Window
Blank Form
Menu and Tool Bars
Program Development Cycle
Our computer program is called a project, application or solution. Software refers to
a collection of instructions to tell the computer what we want done. The computer
only knows what the programmer tells it to do. The programmer must know how to
solve the problem. The programmer will need to determine the output desired, that
is the Graphic User Interface (GUI). Then the programmer needs to determine what
input is required to get the desired output. Next the programmer needs to
determine the processing needed to take the input and end up with the desired
output.
Note, we determine the output first, then the input and then the processing. There
are several tools used by programmers to design a solution to the problem.
Programming Design Tools
Flowcharts (graphic)
Pseudo code (similar to computer code)
Hierarchy Charts (graphical)
Algorithms (list of steps)
You can look up each for more detail. We don’t need to use any of these tools for
our programs.
Program Development Cycle
1. Define the problem
2. Design a solution using a programming tool if desired
3. Create the interface (GUI)
4. Set the properties
5. Write the code
6. Run, test and debug
7. Add any documentation
We will concentrate on steps 3, 4 and 5.
Visual Basic Controls
Visual Basic has many controls and they are found in the toolbox which is usually
on the left side in the IDE.
They can be added to the form by double clicking the control or drag and drop the
control from the toolbox to the form. You can also single click the control, point
where you want the control and stretch to the size you want. We will look at four
controls.
Default names are TextBox1, Button1, Label1 and ListBox1.
Controls have events, properties and methods. The Text Box control is usually used
for input or output. When it is used for output, the Read Only property is usually set
to True. The caption on the Button Control should indicate the effect of clicking the
button. Setting the Text property determines the caption on the button. The Label
Control is used for information. It is usually used to explain the contents of a text
box. Setting the Text property determines the caption in the label. By default, the
Auto Size property is set to True. You will need to set the property to False to be
able to resize the control manually. The List Box control can be used to display
several pieces of information (output). It can be also used to select an item from a
list (input). Programmers usually name their controls with a name that something
to do with its use. They may also prefix the control name based on the type of
control.
Visual Basic Events
An event is an action, such as the user clicking a button. That would be a button
click event. Usually nothing happens in a Visual Basic program until the user does
something that generates an event. What happens depends on how the code is
written by the programmer. The user does something to a control, sometimes
referred to as an object. Visual Basic is an object-oriented language. When the user
does something to an object or control, an event is generated. Sometimes Visual
Basic is called an event-driven language. Each control may have many events and
many are the same for other controls. The default event for button and a label is
the click event. The default event for a text box is the text changed event. The
default event for a list box is selected index change event. The default event for the
form is the form load event. The form load event takes place when the user runs a
program. The programmer can write code for any event.
The code for these event procedures look like this:
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
End Sub
Private Sub Label1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Label1.Click
End Sub
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles TextBox1.TextChanged
End Sub
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
End Sub
End Class
As you can see, the general form is:
Control name_event
The easy way to start an event procedure is to double click the control on the form
in the IDE. This will automatically place something like the above code into the code
window.
The form looks like this:
Numbers
Much of the data processed by computers consist of numbers. The number are
called numeric literals. Numeric literals can NOT contain commas, a dollar sign, a
percent sign or mixed numbers like 8 ½. We use arithmetic operators to process the data.
Arithmetic operators
() used to change the order of operations
^ raises a number to the power of another number
* mutiplies two numbers / devides two number
+ adds two numbers
- subtracts two numbers
A variable is a letter or a name that can store a value in the computers memory.
You can declare a varible by telling the name and the type of varible you want to use. You can assign a value to the variable. You can use a variable by retrieving the
value held by the variable. There are many data types in Visual Basic. Double data
type goes to about 10308. Interger data type goes to about 109 and Single data type goes to about 1038.
We declare a varible with the Dim statement.
Dim speed As Single
Dim time As Single
Dim distance As Double
Or
Dim speed, time As Single, distance As Double
We assign a value to the variable by an assignment statement.
speed = 50
time = 2
We use these variables in a numeric expression.
distance = speed * time
The variable distance will have the value of 100.
Input and Output
A text box can be used for input or output. The content of a text box is stored in
the text property and is always a string. A string is a sequence of characters which
could be letters, numbers or other characters.
Input example:
speed = TextBox1.Text
Now if the text property of TextBox1 contained the number 50, it would actually be
the string 50. Now I can’t multiply strings but I can multiply numbers. There is a
built-in function that will convert the string “50” to a number 50. The function is the
Val function. We will rewrite the code.
speed = Val (TextBox1.Text)
Now the variable speed contains the number 50 and I can perform mathematic
operation with it. We are reading what is already stored in the text box and placing
the value into the variable speed. The function CDbl will convert the string to a
double data type. The function CSng will convert the string to a single data type.
There are many built-in functions.
Notice the format: TextBox1.Text is Control name.Property
Output example:
TextBox1.Text = speed
Here the variable speed already contains a value and we are setting the text
property of the text box. Even if the value in the variable was a number, the value
in the text property of the text box will be a string.
A list box can be used for output but we used the add method to add items to the
collection displayed in the list box.
ListBox1.Items.Add (speed)
Notice the method Add, is preceded with a period and followed with an argument in
parentheses.
Now let us create our first program. We want to write a program that will convert
meters to feet. We will need one input and one output. Now let us look at some
steps to creating a Visual Basic project, solution or application.
Steps in creating a Visual Basic application
Step 1
Create an interface with 2 labels, 2 text boxes and a button.
Step 2
To set the property, single click the control and in the properties window, select the
property that you want to change.
Control Property Value
Label1 Text Enter meters
Label 2 Text Converted to feet
Button1 Text Calculate
Form1 Text Convert
I set many other properties but you don’t have to.
Also set the TabIndex property of TextBox1 to 0. This will make the cursor be in the
textbox and be ready for the user to type in a value.
Control Property Value
Label1 AutoSize FALSE
Label 2 AutoSize FALSE
Label1 Location
x 25
y 45
Label2 Location
x 25
y 135
Label1 Size
Width 110
Height 20
Label2 Size
Width 110
Height 20
TextBox1 Size
Width 110
Height 20
TextBox2 Size
Width 110
Height 20
Form1 Size
Width 300
Height 300
Form1 StartPosition CenterScreen
TextBox1 Location
x 165
y 45
TextBox2 Location
x 165
y 175
Step 3
Write the code for the button click event. Double click on the button while in the
IDE. The code window will open. Type in the following code:
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click Dim m, ft As Single
m = Val(TextBox1.Text) ft = 3.2808 * m
TextBox2.Text = ft End Sub
End Class
Now run the program by pressing F5. Type 10 into TextBox1. Click the button. The
answer (32.808) should be displayed in TextBox2. Always check you run to make
sure it gives the correct answer. There is nothing worse than a program that gives
wrong answers. The run should look like this:
After stopping your run, pull down the File menu and select Save All. This will save
all the files needed for this project. There are many files, not just one file. We
created the GUI, set some properties and wrote some code. Visual Basic is
sometimes called RAD- Rapid Application Development system.
Now let us create our next program. We want to computer the flow in a pipe or duct
given the cross sectional area and the velocity.
Q = AV
Q = flow (ft3/sec)
A = area (ft2)
V = velocity (ft/sec)
We will have two inputs and one output.
Step 1
Create an interface with 4 labels, 3 text boxes and 1 button. It should look
something like this:
Step 2
Set the following properties:
It should look something like this:
Control Property Value
Label1 Text Enter the area in square feet
Label2 Text Enter the velocity in ft / sec
Button1 Text Compute
Label3 Text The flow is:
Label4 Text cu ft / sec
Form1 Text Flow
Double click on the button while in the IDE. The code window will open. Type in the
following code:
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim area, vel, flow As Single
area = Val(TextBox1.Text)
vel = Val(TextBox2.Text)
flow = area * vel
TextBox3.Text = flow
End Sub
End Class
The run (press F5) should look something like this:
Be sure to save all if you get the same answers. If you don’t get the same answers,
check your code for mistakes or the values entered during the run.
I set the TabIndex property of the controls as follows:
When the TabIndex property is set to 0, the cursor will start there. When you press
the Tab key it will move to the next number (1). Press the Tab key again and it
moves to the next number (2) which is the button. You can run this entire program
without using the mouse. Would you rather be fast or half fast? Any time you can
use the keys on the keyboard you will be faster than using the mouse.
Again, we created the Graphic User Interface (GUI). We added labels, text boxes
and a button. Then we set a few properties. Then we wrote a little code. We could
change the program to handle something like:
E = IR
E = voltage
I = current (amps)
R = resistance (ohms)
Or something like:
A = LW
A = area (square feet)
L = length (feet)
W = Width (feet)
I changed many other properties but you only need to set a few properties.
Control Property Value
Label1 Location
x 30
y 25
Label2 x 30
y 60
Label3 x 30
y 170
Label4 x 340
y 170
TextBox1 x 290
y 25
TextBox2 x 290
y 60
Button1 x 181
y 111
TextBox3 x 181
y 170
Form1 Size
Width 500
Height 300
Form1 StartPosition CenterScreen
Built-in Functions (Math)
Visual Basic has many different types of built-in functions like string functions,
conversion function and math functions. Engineers often use math functions so we
will look at the once available in Visual Basic.
Action Function
Derive trigonometric functions. Atn, Cos, Sin, Tan
General calculations. Exp, Log, Sqr
Generate random numbers. Randomize, Rnd
Get absolute value. Abs
Get the sign of an expression. Sgn
Perform numeric conversions. Fix, Int
We can derive many other functions as user defined functions:
Function Derived function
Secant (Sec(x)) 1 / Cos(x)
Cosecant (Csc(x)) 1 / Sin(x)
Cotangent (Ctan(x)) 1 / Tan(x)
Inverse sine (Asin(x)) Atan(x / Sqrt(-x * x + 1))
Inverse cosine (Acos(x)) Atan(-x / Sqrt(-x * x + 1)) + 2 *
Atan(1)
Inverse secant (Asec(x)) 2 * Atan(1) – Atan(Sign(x) / Sqrt(x *
x – 1))
Inverse cosecant (Acsc(x)) Atan(Sign(x) / Sqrt(x * x – 1))
Inverse cotangent (Acot(x)) 2 * Atan(1) - Atan(x)
Hyperbolic sine (Sinh(x)) (Exp(x) – Exp(-x)) / 2
Hyperbolic cosine (Cosh(x)) (Exp(x) + Exp(-x)) / 2
Hyperbolic tangent (Tanh(x))
(Exp(x) – Exp(-x)) / (Exp(x) + Exp(-
x))
Hyperbolic secant (Sech(x)) 2 / (Exp(x) + Exp(-x))
Hyperbolic cosecant
(Csch(x)) 2 / (Exp(x) – Exp(-x))
Hyperbolic cotangent (Coth(x))
(Exp(x) + Exp(-x)) / (Exp(x) – Exp(-
x))
Inverse hyperbolic sine (Asinh(x))
Log(x + Sqrt(x * x + 1))
Inverse hyperbolic cosine (Acosh(x))
Log(x + Sqrt(x * x – 1))
Inverse hyperbolic tangent (Atanh(x))
Log((1 + x) / (1 – x)) / 2
Inverse hyperbolic secant (AsecH(x))
Log((Sqrt(-x * x + 1) + 1) / x)
Inverse hyperbolic cosecant (Acsch(x))
Log((Sign(x) * Sqrt(x * x + 1) + 1) /
x)
Inverse hyperbolic cotangent (Acoth(x))
Log((x + 1) / (x – 1)) / 2
Pi (3.141592654) is built in to Excel but not Visual Basic.
Now let us look at our next program. We want to calculate the angle a road should
be banked when given the velocity, radius of curvature and the force of gravity.
Visual Basic uses radians when using trigonometric functions. To convert from
radians (R) to degrees (D), we use:
Step 1
Create an interface with 5 labels, 3 text boxes, 3 buttons and one list box. The
interface should look something like this:
Step 2
Set some of the properties of the controls.
Notice, there is a “&” character in front of some letters. This will make the letter
underlined and an access key or hot key. The user can press the Alt key and the
letter (Alt + p) to select the button without the use of the mouse. To get 2, I held
down the Alt key while typing the numbers 253 on the numeric key pad. Then let
up on the Alt key.
The interface should look something like this:
Control Property Value
Label1 Text Enter the velocity of the car in ft / sec
Label2 Text Enter the radius of the curve in feet
Label3 Text Enter the force of gravity (earth is 32.2 ft / sec²)
Label4 Text The angle of the banked road is:
Label5 Text degrees
Button1 Text Com&pute
Button2 Text &Quit
Button3 Text &Clear
Step 3
Now, we need to write the code (event procedures) for three buttons. Again, double
click the compute button while in the IDE. The code window should open. Type in
the following code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim vel, rad, grav, trad, tdeg, pi
vel = Val(TextBox1.Text)
rad = Val(TextBox2.Text)
grav = Val(TextBox3.Text)
trad = Math.Atan(vel ^ 2 / (rad * grav))
pi = 3.141592654
tdeg = 180 * trad / pi
ListBox1.Items.Add(tdeg)
End Sub
Press F5 and your run should look something like this:
If you get the same answer, GREAT! If you get something different, check your
code or the numbers you typed in during the run.
In the IDE, click on the Form1.vb [Design] tab. Now double click on the Quit button
and the code window should open. Now we want to add code to the Button2 Click
event. Add the following code:
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button2.Click
Me.Close()
End Sub
Here we are using the close method. Me refers to Form1. Therfore, we are saying close the form which ends the run. Remember I said controls or objects have
properties, events and methods. Note, we used the Add method to add items to the
list box. So a method has a period in front and parenthesis at the end.
We could have used the End statement. This ends the run which also closes the
form. The code would look something like this: Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button2.Click
End
End Sub
Now click on the Form1.vb [Design] tab. Double click on the Clear button. This
should open the code window so you can write the following code. Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button3.Click
TextBox1.Text = ""
TextBox2.Clear()
TextBox3.Text = ""
ListBox1.Items.Clear()
End Sub
For text box 1, I set the text property to a null string (a string with nothing in it).
For text box 2, I used the clear method. You can use either one for a text box. For
list box 1, I used the clear method. A list box does NOT have a text property.
As before, I set many other properties. I set the StartPosition property to
CenterScreen. I set the size of the text boxes to 125, 20. I set the size of the buttons to 110, 25. I set the Form1 size to 550, 400. I set the size of three of the
labels to 300, 25. I set the Location, x value to 35 for three of the labels. I set the
Location, x value of the three text boxes to 385. I set the x and y values of all the controls or objects.
I also set values of the TabIndex of all the controls as shown:
Remember, the user can press the Tab key to navigate from text box 1 (number 0) to text box 2 (number 1) all the way to the Quit button and never use the mouse.
Remember, using the mouse is not as fast. The user can also use the hot key, (p, q
and c). They can hold the Alt key and press p (Alt + p) and it will be the same as
clicking on the Compute button. They can press Alt + q and it will be the same as clicking the Quit button and Alt + c for the clear button.
Be sure to save all when you finish your run and finish setting all the properties. I created the following folders:
C:\Visual Basic 2008\Projects
In the projects folder, I now have three folders for Lab1PDH, Lab2PDH and
Lab3PDH. This was Lab3PDH. In the following path:
C:\Visual Basic 2008\Projects\Lab3PDH\Lab3PDH\bin\Debug
There is a Lab3PDH.exe file. This is the file you can send to your friends and they
can run it if they have Microsoft Net Framework 3.5. It is free and you installed it
when you installed Visual Basic 2008 Express Edition. As you can see many files are
created when you create a Visual Basic Project.
Loops
There are several tyoes of loops used in Visual Basic.
While … End While Do … Loop
For … Next
For … Each Next
The For … Next loop performs the loop a set number of times. It uses a control
variable or counter to keep track of the number of repetions. You specity the
starting value and the end value. The default increment is one. You can specify the increment. The format looks something like this:
For counter [ As datatype ] = start To end [ Step step ]
[ statements ]
[ Exit For ]
[ statements ]
Next [ counter ]
The items in [] are optional.
Examples of For statements:
Now our next program will produce a table. We want the user to enter the value of a resistor in a text box. They will click the button to produce a table in a list box.
We will vary the current and compute the power. We will use the following
equation:
P = I2 R
P = Power (watts)
I = Current (amps)
R = Resistance (ohms or Ω)
Hold the Alt key while typing 234 on the numeric key pad to get Ω.
Step 1
Create the graphic user interface (GUI) with one label, one text box, one button
and one long listbox. The width of the form is 500 and the height is 600. The
interface should look something like this:
Step 2
Set properties as follows:
When we set the form Font property, that is the default font for controls placed on
the form. The label, text box, button and list box all have the same font unless we change it. This will be useful when we try to produce a table with characters that
line-up.
Set the following properties:
Control Property Value
Form1 Font
Name Courier New
Size 10
Form1 StartPosition CenterScreen
Form1 Size
Width 500
Height 600
Control Property Value
Label1 Size
Width 270
Height 23
Label1 Location
x 32
ListBox1 Location
x 32
ListBox1 Size
Width 425
Height 436
Label1 Text Enter the resistance in ohms
Button1 Text &Table
Button1 Size
Width 120
Height 26
The form should look something like this:
Step 3
Now we are about ready to write some code. The items placed in a list box are
string data type. We will use the String.Format method to add items to the list box.
The format or syntax is:
String.Format(format, arg0, arg1, arg2)
We will have three arguments (power, current and resistance). The format item in
the above has a certain format or syntax.
{index[,alignment or length][:format specifier character]}
We will not use the last item (format specifier character).
While in the IDE, double click the button and the code window should open.
Remember to set the TabIndex property of the textbox to 0 and the button to 1.
Write the following code:
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim p, i, r As Single, fm As String
r = Val(TextBox1.Text) fm = "{0,-15}{1,-15}{2,-15}"
ListBox1.Items.Clear() ListBox1.Items.Add(String.Format(fm, "Power", "Current", "Resistance"))
ListBox1.Items.Add(String.Format(fm, "watts", " amps", " Ω")) ListBox1.Items.Add(String.Format(fm, "", "", ""))
For i = 10 To 20 Step 0.5 p = i ^ 2 * r
ListBox1.Items.Add(String.Format(fm, p, i, r)) Next i
End Sub End Class
The first thing is to dimension all our variables. Then we store the value typed into
the text box in the variable r.
Looking at:
fm = "{0,-15}{1,-15}{2,-15}"
The 0, 1 and 2 are the index value of the three arguments. The -15 says you want
it left aligned and 15 characters long. The next four lines of code clear the list box
and display the heading for our table in the list box. The For … Next loop creates a
table of values in our list box.
Press F5 to run the program. The run should look something like this:
I we change the -15’s in, fm = "{0,-15}{1,-15}{2,-15}" , to 15 then the columns
will be right justified.
Again I held down the Alt key while typing the numbers 234 on the numeric key
pad to get the symbol Ω. There are many characters that can be entered this way.
It works with most fonts. This also works in Excel, PowerPoint and of course Word.
Special Characters:
Hold down the Alt key and type 237 from the numeric key pad only to get φ.
Hold down the Alt key and type 241 to get ±.
In engineering, we use the degree symbol a lot. Hold down the Alt key and type
248 to get something like this 27 °F. We also use square a lot. So how would I get
a² + b² = c². That is right Alt + 253. If you can find it on here, use it. That will be
much fast than any other way. In engineering, time is money. If we can save time,
we can make more money.
I hope we covered enough of Visual Basic 2008 to get you interested in learning
more. There are many new books on Visual Basic 2008, some you can download
free from the Internet. One is “Accelerated VB 2008”. Other good books are
“Beginning VB 2008 From Novice to Professional” and “Visual Basic 2008 Step by
Step”. There are many controls like radio buttons, check boxes, timer, combo
boxes, group boxes and picture boxes. that we didn’t cover. We didn’t discuss
strings in detail since engineers use number a lot. Arrays are another useful topic
for engineers. In addition to event procedures, there are sub and function
procedures.