You are on page 1of 44

www.covenantuniversity.edu.

ng

Introduction to Visual Basic


Programming

Lecture Note (Week Five)

1
Graphical User Interface
 A graphical user interface (GUI) allows a user to
interact visually with a program.
 GUIs are built from GUI components (which are
sometimes called controls)
 An example is shown in Fig. 10

2
Fig. 10: Example of a GUI

3
GUI Components
Common Controls

4 4
Assign properties to controls
 Each form and control has properties assigned to it by default when
you startup a new project.
 To view the properties of an object, click on the object (form or
control) in the form window.
 Then, click on the Properties Window or the Properties Window
button in the tool bar.
 Properties can be viewed in two ways: Alphabetic and Categorized.
 A very important property for each object/control is its name. The
name is used by Visual Basic to refer to a particular object in code.
Labels
 Labels provide text instructions or information and
are defined with class Label
– A Label displays read-only text
 Common Label properties are shown in Fig 11.

6
Fig. 11: Common Label properties

7
TextBoxes
 A textbox is an area in which text can either be
displayed by the program or be input by the user via
the keyboard
 A password textbox is a TextBox that hides the
information entered by the user
 Figure 12 and 13 lists the common properties and
events of TextBoxes
8
Fig. 12: TextBox properties and events

9
Fig. 13: TextBox properties and events (cont’d)

10
Buttons
 A button is a control that the user clicks to trigger a
specific action.
 Figure 15 shows the Button properties and events

11
Fig. 15: Button properties and events (cont’d)

12
GroupBoxes and Panels
 GroupBoxes and Panels arrange controls on a GUI.
 For example, buttons with similar functionality can
be placed inside a GroupBox or Panel with Visual
Studio .NET Form designer.
 All these buttons move together when the
GroupBox or Panel is moved.
13
GroupBoxes and Panels
 The main difference between the two classes is that
GroupBoxes can display a caption (i.e., text) and
do not include scrollbars, whereas Panels can
include scrollbars and do not include a caption.
 Figures 16 and 17 show the GroupBox and Panel
properties respectively.

14
Fig. 16: GroupBox properties

15
Fig. 17: Panel properties

16
CheckBoxes and RadioButtons
 These two controls are referred to as state buttons
as they can be in on/off or true/false state.
 A RadioButton is different from CheckBox in that
RadioButtons are usually organized into groups
and that only one of the RadioButtons in the group
can be selected (True) at any time.

17
CheckBoxes and RadioButtons
 A checkbox is a small white square that either is blank
or contains a checkmark.
 When a checkbox is selected, a black checkmark
appears in the box.
 There are no restrictions on how checkboxes are used
– any number of boxes can be selected at a time.

18
Fig. 18: CheckBox properties and events

19
Fig. 19: RadioButtons properties and events

20
PictureBoxes
 A picture box displays an image.
 The image, set by an object of class Image, can be in a
bitmap, a GIF (Graphics Interchange Format), a JPEG
(Joint Photographic Expert Group), icon or metafile
format.

21
Fig. 20: PictureBox properties and events

22
Controls Naming convention

 Naming convention in Visual Basic is to use a three letter prefix (depending


on the object) followed by a name you assign. A few of the prefixes are
 Object Prefix Example
 Form frm frmSimpleInterest
 Command Button cmd, cmdExit, btnStart
 Label lbl lblStart, lblEnd
 Text Box txt txtTime, txtName
 Menu mnu mnuExit, mnuSave
 Check box chk chkChoice
Basic Programming Concepts
• Statement/Command: An instruction to do something. These words can be used
interchangeably most of the time
o E.g.: Interest = 6/100
lblResult = I
• It consists of a variable name, followed by the assignment operator (=), followed by some
sort of expression.

• Keyword: They are reserved words. They have their pre-defined meaning and usage
context.
o Examples: Year, Print, PrintLine Private, Property, Protected, Public, QBColor, Raise, RaiseEvent,
Randomize, Rate, ReadOnly, ReDim, Region, Rem, Remove, Boolean, ByRef, Byte, ByVal, Call,
CallByName, Case, Catch, Cbool, CChar, CDate, CDbl, CDec, Char, ChDir, ChDrive, Choose, Chr, CInt,
Class,Clear, CLng, Close, CObj, Command,Const, Count, CreateObject, CShort, CSng, CStr, CType,
CurDir, Date, DateAdd, DateDiff, DatePart, DateSerial, DateString, DateValue, Day, DDB, Decimal, e.t.c
Typical Visual Basic keywords
 Some Common Keywords for Data manipulation
– DIM: declare and allocate storage space to one or more variables
– DATA: holds a list of values which are assigned sequentially using the
READ Command.
 Keywords for Program flow control
– IF ... THEN ... ELSE: used to perform comparisons or make decisions.
– FOR ... TO ... {STEP} ... NEXT: repeat a section of code a given
number of times. A variable that acts as a counter is available within the
loop.
Typical Visual Basic keywords cont’d

DO ... LOOP {WHILE} or {UNTIL}: repeat a section of code


Forever or While/Until the specified condition is true . The
condition may be evaluated before each iteration of the loop, or
after.

GOTO: jumps to a numbered or labeled line in the program.

As: specify data in a declaration statement.

ON ... GOTO/GOSUB: chooses where to jump based on the


specified conditions.
PRINT: displays a message on the screen or other output control.
Miscellaneous
REM: holds a programmer's comment; often used to give a title to the
program and to help identify the purpose of a given section of code.
Dim, Private, Sub, and Public: Use to define how and where
variables can be used:
Sub: Marks the beginning of a Sub procedure
Val: Converts a string to a number
• Syntax: Val(String)
E.g.: P = Val(txtPrincipal.text)
Operators
1 Arithmetic operator: The simplest operators carry out arithmetic operations.
Operators cont’d
These operators in their order of precedence are:
Operator Operation
^ Exponentiation
*/ Multiplication and division
\ Integer division (truncates)
Mod Modulus
+- Addition and subtraction
 
Parentheses around expressions can change precedence.
VB Data types and Variables
 A variable is a container for storing values during
program execution.
 As the name implies, the value of variable can change during
the course of program execution.
 Variables can be numeric, character or string – these are
referred to as data types
 The VB primitive data types are given in Figures 21 and 22.

30
Naming Variables
A variable must have a name for you to be able to assign values to it.
The variable name should be descriptive of the information they
contain. However, you must adhere to variable naming rule:
 The name must start with a letter, not a number or other character.
 The reminder of the name can contain letters, numbers, and/or underscore
characters (no space, periods or other punctuations are allowed)
 The name must be unique within the variable’s scope (scope refers to the
context in which the variable is defined).
 The name cannot be longer that 255 characters.
 The name cannot be one of the programming language’s reserved words
(keywords).
Fig. 21: Visual Basic primitive data types

32
Fig. 22: Visual Basic primitive data types (cont’d)

33
Variable Declaration

It is a good programming practice to declare a variable before use in


your program.
A variable is declared by indicating its datatype
To appropriately declare a variable, you must first determine its
scope.
Variable Declaration
Variable Scope
In addition to telling what type of data you want the variable to
store, variable declaration should also tell where the variable can
be used. This is referred to as scope of the variable
There are two levels of scope:
1 Local Variable: to define a variable local, use the Dim or Private
keywords. With this declaration, the location of the statement
determines the actual scope of the variable. There are two
locations where a local variable can be defined:
i Procedure level: a variable that is declared inside a procedure and can work only in
that procedure
Format: Dim varname As vartype
Example:
Dim Principal As Integer
 
Procedure level variables declared in this manner do not retain their value once a
procedure terminates.
To make a procedure level variable retain its value upon exiting the procedure,
replace the Dim keyword with Static,
E.g. :
Static MyInt As Integer
Static Rate As Double
ii Form (module) level variables retain their value and are available to all
procedures within that form (module).

Form (module) level variables are declared in the General Declarations


section of a form's (module's) code window. The Dim keyword is used:
 Example:
– Dim MyInt as Integer
– Private MyDate as Date
 
Exercises
 Design an algorithm, draw a flowchart and write a
Visual Basic program to do the following:
– Convert Fahrenheit (F) to Celsius (C) using the formula
C=(5/9)*(F-32)
– Calculate area of a triangle using the formula
area=(0.5)*base*height

38
Exercise
 Question: Create a program that calculates and displays the
average of your Test1 and Test2 marks.
 Solution: The program user enters the Test1 and Test2 marks
to the textboxes Text1 and Text2 and clicks on command1.
 The Label4 is used for displaying the average of the marks
entered on Text1 and Text2, where the other labels (1,2,3) are
used for giving the information to the user.

39
40
Messages and data input/output
 The MsgBox function displays a message, waits for the
user to click a button and returns a value indicating which
button has been chosen.
 The simplest MsgBox contains only a message string and
an OK button.
 The general syntax is
MsgBox(prompt [,buttons] [,title]),
41
Messages and data input/output contd
 prompt: string expression displayed in the message
 buttons: numerical expression that is sum of values specifying the type of buttons to display,
 title: string expression displayed in the title bar.
 Some of the button values are given below.
Value Constant Display
0 vbOKOnly OK button only
1 vbOKCancel OK and Cancel buttons
3 vbYesNoCancel Yes, No and Cancel buttons
4 vbYesNo Yes and No buttons
5 32 vbQuestion Query icon
48 vbExclamation Warning message icon , etc

42
InputBox function
 The InputBox function creates and displays a simple
dialogue box that contains a prompt, an edit box, and OK
and Cancel buttons.
 You use this box to allow the user to input data at run-
time.
 The format of the InputBox function is InputBox(Prompt,
[,title] [,default] [,xpos] [,ypos])
43
InputBox function contd
 prompt: a string expression displayed in the box,
Optional arguments
 title: a string expression displayed in the dialogue box’s title bar. If
omitted nothing is displayed.
 default: default response if no input provided
 xpos, ypos: specify the horizontal and vertical position of the box.
If omitted the box is centred horizontally and about one-third of
the way down the screen.
44

You might also like