Lecture6 VARIABLES

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

Computer Principles II

ASST. LECT. ZAHRAA A. NEJIM

The Southern Technical University/ BETC/ Control and Automation


Eng. Tech.
2nd Stage/ 2020-2021
Computer Principles II - Asst. Lect. Zahraa A. Nejim

EVENT PROCEDURE
When you create a program in Visual Basic, you'll generally be doing event-driven
programming. Event-driven programming means that most of the code you write will
be run as users do things within your program or even when certain things happen in
Windows--when events occur. Of course, programming this way means that you have
to know when events occur and have to write code that will make your program do
something in response to the event.

Common Events of Visual Basic Controls

Event Occurrence

Change The user modifies text in a combo box or text box.

Click The user clicks the primary mouse button on an object.

DblClick The user double-clicks the primary mouse button on an object.

DragDrop The user drags an object to another location.

DragOver The user drags an object over another control.

GotFocus An object receives focus. (A text box has the focus whenever it is ready
to accept typing; that is, whenever it contains a blinking cursor.)

KeyDown The user presses a keyboard key (any key) while an object has focus.

KeyPress The user presses and releases a keyboard key(any key) while an object
has focus.

KeyUp The user releases a keyboard key while an object has focus.

Event Occurrence

LostFocus An object loses focus.


Computer Principles II - Asst. Lect. Zahraa A. Nejim

MouseDown The user presses any mouse button while the mouse pointer is over an
object.

MouseMove The user moves the mouse pointer over an object.

MouseUp The user releases any mouse button while the mouse pointer is over an
object.

Example:
1. Create an interface as the below form:

TextBox

Command

2. Double-click on the text box. A window, called the Code window, appears. Just
below the title bar are two drop-down list boxes. The left box is called the Object
box and the right box is called the Procedure box. (When you position the mouse
pointer over one of these list boxes, its type appears.)
Computer Principles II - Asst. Lect. Zahraa A. Nejim

3. Write the below source code:


Computer Principles II - Asst. Lect. Zahraa A. Nejim

5. Now run the program by pressing F5.

6. Once running the program the textBox text becomes green and the font size equals
to 24. This calls the event procedure Text1_GotFocus since the cursor is inside the
TextBox1.
Private Sub Text1_GotFocus()
Text1.Font.Size = 24
Text1.ForeColor = vbGreen
Text1.FontItalic = False
End Sub

7. Press the Tab key (in your keyboard). The contents of the text box will be italic and
the ForeColor is blue. When Tab was pressed, the TextBox lost the focus; that is, the

.
event LostFocus happened to TextBox1 Thus, the event procedure Text1_ LostFocus
was called, and the code inside the procedure was
executed.
Private Sub Text1_LostFocus()
Text1.Font.Italic = True
Text1.ForeColor = vbBlue
End Sub

8. Then, directly the following message Box will appear due


to activating the code inside the event procedure
Command1_GotFocus().
Private Sub Command1_GotFocus()
MsgBox ("Command Got Focus Event")
End Sub
Computer Principles II - Asst. Lect. Zahraa A. Nejim

8. Press the Tab key again to move the cursor (and, therefore, the focus) to the text box.
This calls the event procedure Text1_GotFocus.

9. Click on the TextBox. This calls the event procedure Text1_ Click(), which change text
color to red and bold formatting .
Private Sub Text1_Click()
Text1.ForeColor = vbRed
Text1.Font.Bold = True
End Sub

10. Keep the cursor in the TextBox1 and press any key in your keyboard for example
Shift. The Text1_KeyUp event procedure will be activated and will show the below
message:
Private Sub Text1_KeyUp(KeyCode As Integer,
Shift As Integer)
MsgBox ("Text key Up Event (ANY keyboard
key)")
End Sub

11. Adding or deleting characters in the TextBox1 will activate the Text1 Change event
procedure, which will change the TextBox font size to 20.
Private Sub Text1_Change()
Text1.Font.Size = 20
End Sub
Computer Principles II - Asst. Lect. Zahraa A. Nejim

NUMBER

Numeric data are data that consists of numbers, which can be computed
mathematically with various standard operators such as add, minus, multiply, divide
and so on. In Visual Basic, the numeric data are divided into 7
types, they are summarized in the below Table: Type Storage
Byte 1 byte
Integer 2 bytes
1. Numbers must not contain commas, dollar signs, or percent Long 4 bytes
signs. Also, mixed numbers, such as 8 1/2, are not allowed.
Single 4 bytes

2. Parentheses should be used when necessary to clarify the Double 8 bytes


meaning of an expression. When there are no parentheses, the
Currency 8 bytes
arithmetic operations are performed in the following order:
Decimal 12 bytes

1- ( ) Inner to outer, left to right


2- ^ Left to right in expression
3- */ Left to right in expression
4- + – Left to right in expression

Arithmetic Operations
The five arithmetic operations in Visual Basic are addition, subtraction, multiplication,
division, and exponentiation. Addition, subtraction, and division are denoted in Visual
Basic by the standard symbols +, –, and /, respectively. However, the notations for
multiplication and exponentiation differ from the customary mathematical notations.

Mathematical Notation Visual Basic Notation

a·b or a x b a*b

a^r
ar
Computer Principles II - Asst. Lect. Zahraa A. Nejim

(The asterisk [*] is the upper character of the 8th key. The caret [^] is the upper
character of the 6th key.)

You can show a number on the screen by displaying it in a picture box. If


n is a number, then the instruction:

Picture1.Print n

displays the number n in the picture box. Another important method is Cls. The
statement

Picture1.Cls

erases all text and graphics from the picture box.

Example:
• Draw the following VB6 interface:
• Name the PictureBox1 as picResults.
• Write the below source code:
PictureBox
picResults.Cls
picResults.Print 3 + 2 Command
picResults.Print 3 - 2
picResults.Print 3 * 2
picResults.Print 3 / 2
picResults.Print 3 ^ 2
picResults.Print 2 * (3 + 4)
• Run the program and the output is as following:

SCIENTIFIC NOTATION
Let us review powers of 10 and scientific notation.
Our method of decimal notation is based on a
systematic use of exponents:
Computer Principles II - Asst. Lect. Zahraa A. Nejim

In Visual Basic, b·10r is usually written as bEr. (The letter E is an abbreviation for
exponent.) The following forms of the numbers just mentioned are equivalent.

The computer displays r as a two-digit number, preceded by a plus sign if r is positive


and a minus sign if r is negative.

The process of calculating ar is called raising a to the rth power. Some other types of
exponents are the following:

Example:
The following program illustrates scientific notation. The computer’s choice of whether
to display a number in scientific or standard form depends on the magnitude of the
number.

Private Sub cmdCompute_Click()

picResults.Cls

picResults.Print 1.2 * 10 ^ 34

picResults.Print 1.2 * 10 ^ 8

picResults.Print 1.2 * 10 ^ 3

picResults.Print 10 ^ -20 PictureBox as picResults


picResults.Print 10 ^ -2 Command as cmdCompute
Computer Principles II - Asst. Lect. Zahraa A. Nejim

End Sub

[Run and then click the command button.]

The output is:

Conditional Operators
To control the VB program flow, we can use various conditional operators. Basically,
they resemble mathematical operators. Conditional operators are very powerful tools,
they let the VB program compare data values and then decide what action to take,
whether to execute a program or terminate the program and etc. These operators are
shown in below Table:

Logical Operators
In addition to conditional operators, there are a few logical operators which offer added
power to the VB programs. There are shown in below Table:

Operator Meaning
And Both sides must be true
or One side or other must be true
Xor One side or other must be true but not both
Not Negates truth
Computer Principles II - Asst. Lect. Zahraa A. Nejim

VARIABLES
Variables are used by Visual Basic to hold information needed by your application. Rules
used in naming variables:

• No more than 255 characters.


• They may include letters, numbers, and underscore (_).
• The first character must be a letter.
• Visual Basic does not distinguish between uppercase and lowercase letters used
in variable names.
• You cannot use a reserved (Restricted) word (word needed by Visual Basic) as
names of variables. For instance, the statements print = 99 and end = 99 are not
valid. Some other common restricted keywords are Call, If, Let, Select, and Sub.
If a keyword is used as a variable name, you will soon be warned that something
is wrong. As soon as the cursor is moved from the line, an error message will
appear, and the line will turn red. The use of some other keywords (such as
Error, Height, Name, Rate, Time, Val, Width, and Year) as variable names does
not trigger an immediate warning, but generates an error message when the
program is run.

Variable Declaration
• Most major programming languages require that all variables be declared
before they can be used. Although declaring variables with Dim statements is
optional in Visual Basic, you can tell Visual Basic to make declaration
mandatory. The steps are as follows:

a. From any code window, click on the down-arrow to the right of the Object
box and click on (General).
Computer Principles II - Asst. Lect. Zahraa A. Nejim

b. Type

Option Explicit

and press Enter.

• Then, if you use a variable without first declaring it in a Dim statement, the
message “Variable not defined” will appear as soon as you attempt to run the
program. One big advantage of using Option Explicit is that mistypings of
variable names will be detected. Otherwise, malfunctions due to typing errors
are often difficult to detect.
• Variables are normally declared in the general section of the codes' windows
using the Dim statement. The format is as follows:

Dim variableNmae as DataType

For Example:
Dim password As String

Dim yourName As String

Dim firstnum As Integer

Dim secondnum As Integer

Dim total As Integer

Dim doDate As Date

• Variables that are not (explicitly) declared with Dim statements are said to be
implicitly declared. Such variables, which have a data type called Variant, can
hold strings, numbers, and several other kinds of information.
• For string declaration, there are two possible formats, one for the variable-
length string and another for the fixed-length string. For the variable-length
Computer Principles II - Asst. Lect. Zahraa A. Nejim

string, just use the same format above. However, for the fixed-length string,
you have to use the format as shown below:

Dim VariableName as String * n, where n defines the number of characters the


string can hold.

Dim yourName as String * 10, yourName can holds no more than 10 Characters.

There are three ways for a variable to be typed (declared):

1. Default

2. Implicit

3. Explicit

• To implicitly type a variable, use the corresponding


suffix shown below in the data type table. For
example,

TextValue$ = "This is a string" :creates a string variable

Amount% = 300 :creates an integer


variable.

• Global level variables retain their value and are available to all procedures
within an application. Global declarations are only allowed in the General
Modules. Module level variables are declared in the declarations part of the
general object of a module's code window. (It is advisable to keep all global
variables in one module.) Use the Global keyword:
Global MyInt as Integer
Global MyDate as Date
Computer Principles II - Asst. Lect. Zahraa A. Nejim

 You can add a Module to your application from


the Project menu then select Add Module.

• Constants, once declared and initialized cannot be changed (hence the name
constant' and are declared using the Visual Basic Const keyword. The syntax
for declaring variables is as follows:

Const constName as datatype = value


Computer Principles II - Asst. Lect. Zahraa A. Nejim

• When a variable is declared within a Procedure level scope it is only available


to that procedure unless declared in the general part of the application.
In the below source code and output, the var1 variable is declared inside
command1 so it is not available in command2 since it is local to its procedure.

 Once var1 is declared in the General part, it becomes defined to all


form1 procedures.
Computer Principles II - Asst. Lect. Zahraa A. Nejim

• When a variable is declared with Procedure level scope it only exists while the
code in the corresponding procedure is executing. Once the procedure
completes, the variable and the variable assigned to it are destroyed. Under
certain circumstance it may be necessary for the variable and the current value
assign to it to persist beyond the life of the procedure. Next time the
procedure is called, therefore, the variable still holds the value it held on the
previous invocation of the procedure. The syntax to declare a static variable is
as follows:

Static variableName as datatype

You might also like