Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 90

SHASHEMENE TVET COLLEGE

Data base Administration


Level IV

Unit of Competence: Apply object-oriented programming language skills

Module Title: Applying object-oreented programming language skills

LG Code: EIS DBA4 LG05 M05 LO1-05

TTLM Code: EIS DBA4TTLM 0811v01

LO1- Apply basic language syntax and layout

LO2- Apply basic OO principles in the target language


LO3- Debug code
LO4-Document activities
LO5-Test code

Page 1
Information EIS DBA4-
LG05 M05 LO1 – IS01 Apply basic language syntax and layout

1- Observe basic language syntax rules and best practices

All languages are subject to a set of rules governing


 the set of valid characters that can be used
 word construction
 sentence construction
The rules of sentence construction are called syntax
To use a language correctly you need to know about these and
 vocabulary - the set of valid words
 semantics - ensuring that what is written makes sense
You need to be able to recognize language 'tokens'

Syntax vs. Semantics

Syntax - the grammatical arrangement of words to show their connection and relation; the set of
rules governing this arrangement
Semantics - relate to meaning in language
 A sentence in English may be syntactically correct it obeys the language rules
 But not necessarily semantically correct it has no valid meaning
 Both syntax and semantics are important
Programming Language Building Blocks

 A computer program is like a set of instructions


 each instruction is termed a statement
 Each program statement has a terminating character
 Translate into syntax diagrams

Types of Statement
It’s useful to categorize statements
o type definitions - introduce new types
o variable declarations - introduce new objects
o assignment statements - involve a change in the value of an object
o I/O statements
o compound statements - a (bracketed) collection of statements
o control-flow statements - change the normal linear flow of control (selection,
repetition, function)
o other forms of statement

Page 2
A First C++ Program
PROBLEM:
Display a Greeting

DESIGN:

Hell
o
Display “Hello”

Display your name

Display “welcome to MIS442”

En
d
IMPLEMENTATION:
#include <iostream.h>
int main()
{
cout << "Hello ";
cout << "Your name" << endl;
cout << "Welcome to MIS442" << endl;
return 0;
}
Structure Of Simple C++ Programs
 C See syntax diagram simple C++ program
 We’ll gradually introduce the different forms of statement that you can write in C++
o The cout "..." ...; lines in the greeting program are statements that produce output
 Special significance of main() and the braces { and }
 Your programs must conform to the syntax rules of the language, as specified in the
syntactic elements
 The syntax rules allow the computer to distinguish between syntactically correct and
syntactically incorrect programs
 But what if a program doesn't conform?
++ Compiler-Time Errors
What if you make a syntax mistake in your source program?

 A single syntax error may give rise to multiple compiler error messages.
 You’ll have to get used to the form of the compiler’s error messages.
 It may be worth fixing the first source-code error and then recompiling.

Overall Layout Of C++ Programs

Page 3
 C++ is a free-format language
 The compiler ignores white space (spaces, tabs, end of line, blank lines) in most
situations
#include <iostream.h>
int main()
{
cout << "Hello ";
cout << "Your name"
<< endl;
cout << "Welcome to MIS442"
<< endl;
return 0;
}
 Use indentation and white space to make your programs more readable. The compiler
doesn’t care about white space
Comments
 Program statements alone are often not very readable
 Often you wish to add some commentary to a program
 Such comments give the reader additional information
 There has to be a syntactic element in the language to permit this – see comment//

Comments: Style Rules


 A program without any comments is a bad program.
 A comment should add something to the program.
 And not just expand on the obvious.
 Add comments while you are implementing your program.
 Capture design abstractions as comments in the source code.

Page 4
 Use white space to improve their readability.
 A source file should identify the name and purpose of the program, and its author
and date.
 Use a template for new programs.

Program statement
-A program statement is an instruction to the computer. Eg. cout<<”hellow ICT “;
- The program statement ends with semicolon.
Output using cout- causes the string between the double quotation marks to be displayed on
the screen
Input using cin- e.g cin>>n; causes the program to wait for the user to type in a number.. the
numbered entered by the user is placed in the variable n.

2- Use language data types, operators and expressions

What is a variable?
-Variables: - is a symbolic name that can be given a variety of values.
- Variables are stored in particular places in the computer’s memory.
- An identifier is a name given to various program elements.
- A variables must be declared before it can be used in a program.
- A declaration associate variables with a specific data types.
- The general format of variable declaration is the following.
Data type variable name;
e.g int X;
long Z;
char x,y ;

Data type in C++

C++ has different types of data types. The following are built in data types in C++
Int- 2 byte
Char- 1 byte
Float- 4byte
Double- 8byte
Long-4byte
Long double-10 bytes

Qualifiers
Basic data types can be modified using qualifier
 The unsigned qualifier can be used to quality int, long or char data types. Example
unsigned in x; X can hold only positive integers.
 The other qualifier is the const qualifier. It is used to declare a constant variable.
Examples : const int X=10;
Const float PI=3.14;
 Note; constant is a variable whose value doesn’t change during program execution.

Page 5
Initialization (expression)

This is the process of assigning values to variables at the point of declaration.


Example int X=10;
Float p=10.5;
Cahr X=’C’;

Note: in C++ equal to(=) is used for assignment statement.


In the above example ‘C’ is a character constant, 10 is an integer constant and 10.5 is a float
constant.

Operators

C ++ has different types of operators. Such as


1-Artimetic operators: - C++ uses the four normal arithmetic operators +,-,* and / for addition,
subtraction, multiplication and division. In addition there is a remainder operators and it is
represented by %. It works only with integer variables. E.g 7%4=3 5%9=4 5/9=0 5.9/9=0.44

2- Arithmetic Assignment operators: assume in our program we have the following


Code X=X+Y;
X+=Y; a shorter form of X=X+Y;
Using arithmetic assignment operators we can re write the above statement as follows X+=Y;

Note: there are arithmetic assignment operators corresponding to all the arithmetic operators:+=,
-=, *= , %=
X-=Y; X=X-Y;
X*=Y;X=X*Y;
X%=Y;X=X%Y;

3-Increment and declaration operators

Assume we have the following code in our program. X=X+1; we can rewrite the above code in
the following short form X++;
The ++ operators adds 1 to its argument. Similarly we have a decrement operator that subtracts 1
from its argument X--; it is equivalent to X=X-1;

4-Relational operators
A relational operator compares two values. The comparison involves such relationships as equal
to, lessthan, greater than, less or equal to and so on.

Description C++
Equal to ==
Less than <
Greater than >
Not equal to !=
Less or equal to <=
Greater or equal to >=
Page 6
5-logical operators:
Used to combine Boolean expressions formed from relational operators
There are three logical operators
And &&
Or!!
Not!
Prefix and postfix
Note: - Assume we have the following code in our program
Int x=10;
Int y=x++;
After the execution of the above code the value of y is 10 because the assignment is done before
the increment.
The above expression is a postfix expression
If the code in our program were
Int x=10;
Int y=++x;
Y will be assigned a value of 11 because the increment is done before the assignment. The above
expression is called prefix expression.
Example what is the output of the following program
# include<iostream.h>
Void main ( ) output
{ 10 12 12
Int x=10;
Cout<<x++;
Cout<<++x;
Int y=x--;
Cout<<y;
}
#include<iostream.h>
Void main( )
{
Int x=10;
Cout<<++x; out put
Cout<<x++; 11 11 11 11
Int y=--x;
Cout<<y;
Cout<<x;
}
Manipulator
Manipulator are operators used with the insertion operators<< to modify the way data is
displayed.
The endl manipulator:-This manipulator has the same effect as the \n character. Characters
The setw manipulator:- causes the number(string) that follows in the Stream to be printed with
in a field in characters wide where n is the argument to setw(n)
Example cout<<endl<<500;
Cout<<endl<<setw(7)<<500;
Page 7
Example:-write a C++ program whose out put is the following tables
Year Number
1990 10000
1991 500
1992 1000000
1993 100000

Solution
#include<iostream.h>
#include<iomanip.h>
Void main
{
Cout<<endl<<”year”<<setw(10)<<”number”;
Cout<<endl<<1990<<setw(10)<<10000;
Cout<<endl<<1991<<setw(10)<<500;
Cout<<endl<<1992<<setw(10)<<1000000;
Cout<<endl<<1993<<setw(10)<<100000;
}
Escape sequence –there are characters with special meanings
e.g. \n new line \t tab

3- Use the appropriate language syntax for sequence, selection and iteration
constructs
Control statement
Control statement is a program statement that causes a jump from one part of the program to
another depending on calculations performed in the program.
There are two major categories of control statements
 branching(decision)selection statements
 loops
I-Branching statements
Causes one-time jump to a different part of the program, depending on the value of an
expression.
We have three types of decision statements
 if ….. else statements
 switch statements
 conditional operators statements
A-The if ….. Else statements
Syntax
If (test expression)
Statements;
Else
Statements;
 if ….. else statements can be used without the else as a simple if statement
If (test expression)
{
Statements;

Page 8
}
Nested if……….. Else statement
If …else statements can be nested in each other’s to select one choice from multiple choose
Syntax
If (test expression 1)
If (test expression 2)
Statement 1;
Else statement2;
Else
If (test expression 3)
Statement 3;
Else
Statement 4;
Statement 1 will be executed when both test expression 1 and test expression 2 are true
A better way of handling multiple conditions is to use the
If…..else ---if…else structure

Syntax
If (test expression 1)
Statement;
Else If (test expression)
Statement;
Else If (test expression)
Statement;
Else
Statement;
Example1:- write a C++ program that finds the roots of quadratic equation

R1,R2= -b+√b2-4ac

2*

#include<iostream.h>
#include<conio.h>
#include<math.h>
Void main ( )
{
Float a,b,c,des, R1,R2 ;
Cout<<”\n enter the three coefficients”;
Cin>>a>>b>>c;
Des=b*b-4*a*c;
If(des==0)
{
R1=-b/(2*a);
Cout<<”root=”<<R1;
}
Else if(des>0)
Page 9
{
R1=(-b+sqrt(des))/(2*a);
R1=(-b-sqrt(des))/(2*a);
Cout<<”\n root1=”<<R1;
Cout<<”\n root1=”<<R2;
}
Else
Cout<<”\n no solution”;
Getch();
}
Example2:- write a C++ program that checks whether a number interred by the user is greater
than, less than or equal to 100.
#include<iostream.h>
#include<conio.h>
Void main( )
{
Int n;
Cout<<”\n enter the number”;
Cin>>n;
If (n>100)
Cout<<”\n the number is greater than 100”;
Else if (n<100)
Cout<<”\n the number is less than 100’;
else
Cout<<”\n the number is equal to 100’;
Getch();
}

B-The switch statement


Switch statement:-is used for long decision trees where condition depends on the value of a
single variables of int or char type.
Syntax:
Switch (var)
{
Case var1:
Statement …
Statement;
Break;
Case var2:
Statement …
Statement;
Break;

Case var n:
Statement …
Statement;
Break;
Page 10
Default:
Statement;
}

Example1:-write a C++ program that accepts the grade of a student and prints out the
corresponding description of the grade.
Grade Description
A Excellent
B Very good
C Grade
D Poor
F Fair

Solution
#include<iostraeam.h>
Void main ( )
{
Char X;
Cout<<”\n enter student grade’;
Cin>>X;
Switch(X)
{
Case ‘A’:
Cout<<”\n excellent”;
Break;
Case ‘B’:
Cout<<”\n V.good”;
Break;
Case ‘C’:
Cout<<”\n Good”;
Break;
Case ‘D’:
Cout<<”\n poor”;
Break;
Case ‘F’:
Cout<<”\n Failed”;
Break;
Default:
Cout<<”\n invalid letter grade”;
}
}
Example2:-write a C++ program that accepts the score of a student and displays the
corresponding result using the following table.
Score Grade
80-100 A
Page 11
60-79 B
40-59 C
20-39 D
0-19 F
>0 invalid result

Solution
#include<iostraeam.h>
# include<conio.h>
Void main ( )
{
Int X;
Cout<<”\n enter the student score”;
Cin>>X;
Switch(X)
{
If(80<=X&&X<=100)
Cout<<” grade is A”;
Else If(60<=X&&X<80)
Cout<<” grade is B”;
Else If(40<=X&&X<60)
Cout<<” grade is C”;
Else If(20<=X&&X<40)
Cout<<” grade is D”;
Else If(0<=X&&X<20)
Cout<<” grade is F”;
Else
Cout<<”\n invalid result”;
Getch( );
}
}
C-The conditional operator
Assume we have the following code in our program
If(a>b)
Max=a;
Else
Max=b;
We can rewrite the above code in a shorter from using the conditional operator as follows
Max= (a>b)? a:b;
Example: write a C++ program that finds the absolute value of an integer
Solution
#include<iostraeam.h>
Void main ( )
{ int X;
Cout<<”\n enter the number”;
Cin>>X;
If(X>=0)
Page 12
Cout<<”\n Absolute value=”<<X;
Else
Cout<<”\n Absolute value=”<<-X;
}
Abs=(X>=0)?X:-X;
Z=(X>=0)?X:-X;
Cout<<”absolute value=”<<Z;
}

II-LOOPS

Loops are control statements that allow a group of statements that allow a group of
statements (or a statement) a number of times
 we have three types of lopps in C++
o for loop
o while loop
o do loop (dowhile loop)

A-The for loop statement


- It is more suitable to situations in which we know the number of times the group of
statements have to be reapeated.

Syntax
For( intialization exp;test expertion; increment)
Body of for loop;
- The intialization expression is expected only once, when the loop first starts. It gives the
loop variable an initial valu.
- The test expression usually involves a relational operator. It is evaluated each time
through the loop; just before the body of the loop is executed
It determines whether the loop will be executed again.
- The increament expression changes the value of the loop variables

e.g. for(i=0;i<5;i++)
{
Statements;
}
I=0,i=1;i=2;i=3;i=4

Example
What is the out put of the following program?
# include<iostream.h>
Void main( )
{
Int i;
for(i=0;i<10;i++)
{

Page 13
Cout<<endl<<”square of ”<<i<<’\t’<<i*i;
Cout<<endl<<”square of ”<<i<<’\t’<<i*i*i;
}
}

Out put
Square of Cube of
0 0 0 0
1 1 1 1
2 4 2 8
3 9 3 24
4 16 4 64
5 25 5 125
6 36 6 216
7 49 7 343
8 64 8 512
9 81 9 729

B-The while loops structure

If we don’t know how many times the loop will be expected in advance, we have to use while
loop.
Syntax while (test expression)
Statement;

Example
A C++ program that calculates the sum and mean of n integers
#include<iostream.h>
Void main( )
{ int n=0;
Float sum, avg, x ;
Sum=0;
Char y=’y’;
While (y==’y’)
{
Cout<<”\n enter a number”;
Cin>>x;
Sum= sum+x;
n++;
Cout<<”\n more number ;( y/n)”;
Cin>>y ;
}
Avg=sum/n;
Cout<<”\n sum=”<<sum;
Cout<<”\n avg=”<<avg;
Page 14
}

C-Do …….while loop

If we want the loop to be expected at least once, we have to use do loop.


Syntax
Do {
Statements;
{
While (test expression);
Example1: - what is the output of the following programs.

#include<iostream.h>
Void main ( ) out put
{
int x=10; 10
int i=0; 11
for (i=0;i<5;i++) 13
{ 15
If (x%2==0) 17
Cout<<endl<<x;
Else
Cout<<endl<<x++;
X++;
}
}

Example2: - what is the output of the following programs.


#include<iostream.h>
Void main ( ) out put
{ 10
int x=10; -9
while (x>0) 8
{ -7
If (x%2==0) 6
Cout<<endl<<x; -5
Else 4
Cout<<endl<<-x; -3
X--; 2
} -1
}
4-Use arrays and arrays of objects
Page 15
Array:-in every life we group similar objects in to units. In computer language also we need
to group similar data items.
- Arrays are mechanisms in which we group similar data items.

What is an array?
An array is a mechanism to group data items of similar type in to a unit.
Example:- write a program that accepts the results of 5 students and displays their result
with their corresponding grade.
Result Grade
>80 A
60<X<=80 B
40<X<=60 C
20<X<=40 D
X<=20 F
Solution
#include<iostream.h>
Char check(float x)
{
If(x>80)
Return ‘A’;
Else if(60<x&&x<=80)
Return ‘B’;
Else if(40<x&&x<=60)
Return ‘C’;
Else if(20<x&&x<=40)
Return ‘D’;
Else
Return ‘F’;
}
Void main( )
{
Float S1,S2,S3,S4,S5;
Char grade;
Cout<<”\n enter the results of the students”;
Cin>>S1>>S2>>S3>>S4>>S5;
Grade=check(S1);
Cout<<”\n Result=”<<S1<<”\t Grade=”<<Grade;
Grade=check(S2);
Cout<<”\n Result=”<<S2<<”\t Grade=”<<Grade;
Grade=check(S3);
Cout<<”\n Result=”<<S3<<”\t Grade=”<<Grade;
Grade=check(S4);
Cout<<”\n Result=”<<S4<<”\t Grade=”<<Grade;
Grade=check(S5);
Page 16
Cout<<”\n Result=”<<S5<<”\t Grade=”<<Grade;
}

Lets us do the above program using an array

# include<iostream.h>
Char check(int);
Void main( )
{
Int stud[5];
Cout<<”\n enter the results of the students”;
For(int i=0;i<5;i++)
Cin>>stud[i];
Char Grade[5];
For( i=0;i<5;i++)
{
Grade[i]=check(stud[i]);
}
For( i=0;i<5;i++)
Cout<<endl<<”Result=”<<stud[i]<<”\t Grade=”<<grade[i];
}

Defining Arrays

Like other variables, an array must be defined before it can be used to store information
- An array definition specifies a variable type and a name it also include the size
- The size specifies how many data items the array will contain.
- The size is surrounded by a sequence brace lets.
Int stud[5];
Char grade [5];

Data type name size

Example: using array write a program that calculates the sum and mean of 20 integer items.

# inculde<iostream.h>
Void main( )
{
Int a[20];
Cout<<”\n enter the numbers”;
For(int i=0;i<20;i++)
Cin>>a[i];
Int sum=0;
For(int i=0;i<20;i++)
Sum=Sum+a[i];
Page 17
Float mean=((float)sum)/20;
Cout<<”\n sum=”<<sum;
Cout <<”\n mean=”<<mean;
}

Self-Check EIS DBA4-


Apply basic language syntax and layout
LG05 M05 LO1-SC01

Name: _________________________ Date: _______________

____1-which one of the following is rule of sentences construction


A- Inheritance B- semantics C- syntax D- vocabulary
____2- ___ is a symbolic name that can be given a variety of values.
A- Data type B- semantic C- integer D- variable
____3- a variable must be declare in ____
A- After the program is used B- before the program is used
B- In the body of the program D- B and C
____4- ____ is a process of assigning values to variable at the point of declaration.
A- Initialization B- declaration C-inheritance D- All
____5- ___ is a mechanism which groups similar data items
A- Initialization B- arrays C-inheritance D- A and C
____6- ____ is the manipulator operator used for the new line in C++
A- Endl B- new line C-\n D- A and C
____7- which of the following is relational operator
A- And (&&) B- + (addition) C- not (!) D- equal to (==)

Page 18
Answer Key EIS DBA4-LG05
Apply basic language syntax and layout
M05 LO1-AK 01

1-C
2-D
3-B
4-A
5-B
6-D
7-A

Page 19
Information Sheet- EISDBA4-LG05
M05 LO2-IS02 Apply basic OO principles in the target
language

1- Implement a class that contains primitive member/ instance variables


What is object oriented programming language?
- Object is an entity that allows a programmer to encapsulate a type’s declaration a
long with declarations of operators to manipulate variables of that type.
Are a natural means of implementing abstract data type
- Inheritance –one characteristics of objects is that descendant Objects inherit
information and operators from previous declared a casters types.
- Object –oriented programming is the use of objects and inheritance
o It is one approach to programming that involves combining data and
functions that operates on that data.
o It must have three core technologies namely encapsulation, inheritance and
polymorphism.
Characteristics of object-oriented language
- Objects- when you are approach a programming problem in an object-oriented
language, you no longer ask how problem will be divided in to functions, but how it
will be divided in to objects.
- Classes-is a collection of similar objects
Objects- is an instance of a class
- Inheritance –a class are created according to hierarchies and inheritance allows the
structure and method in one class to be passed down the hierarchy
o Inheritance is the process of creating new classes, called derived classes from
existing classes.
- Reusability – once a class has been written, created and debugged, it can be
distributed to other programmers for use in their own programs.
- Creating new data types- one of the benefits of objects is that they give the
programmer a convenient way to construct new data types.
- Polymorphism and overloading- one thing with distinct forms.
Example
Student is class
Whereas student Abebe is object of class student
Class car class chair
Toyota –object arm chair- object
- A class has some properties associated with it
- For example some of these properties of class student are

Page 20
o Id, name, department , gender , birth date
- The above properties are data members of the class student
- There are also other properties of class students that can be obtained through some
calculation
o Semester tuition fee
o Cumulative GPA
o Age
- These properties are function members of the classes student
Example: - identify the data members and function members of class rectangle
Data member Function member
-Kind of rectangle - Age
-Height -Perimeter
-Width -Diagonals
-Angle
Example: - identify the data members and function members of class car
Data member Function member
-Weight - Average speed
-Color -Fuel consumption
-Motor number

2- Implement a class that contains multiple options for object construction

Class instantiation
- To create an instance of any class the general format is
Class name variable name;
Example: rectangle R1;
R1 is an instance of class rectangle
- Once an instance of class is created, we can access the public member through the dot
operators
- Example – to access area the syntax is R1.area( );
Class constructions
- In the above example the name of the class is rectangle. It has two data members, height
and width and it has three function members’ area, perimeter and get data.
- To write any class we begin with the key word class followed by the name of the class.
- The body of the class starts with opening curly brace and ends with a closing curly brace
followed by semicolon.
Private and public key words
Inside the class we have two key words, private and public.
- When a member of a class is declared to be private it can only be assessed inside the class
.we cannot use outside the class for e.g. in void main ( )
- When a member of a class is declared to be public it can be assessed both side and
outside the class.
Declaring a class
Example the member of a class are represented by variable and function members are
represented by function specifying the class rectangle.

Page 21
Let us write the complete C++ program for the class rectangle
#include<iostream.h>
Class rectangle {
Private:
int width, height;
Public:
Void area ( )
{
Cout<<”Area=”<<width * height;
}
Void perimeter ( )
{
Cout<<”perimeter=”<<2*(width + height)
}
Void getdata ( )
{
Cout<<”\n enter width”;
Cin>>width;
Cout<<”\n enter height”;
Cin>>height;
}
};
Void main ( )
{
Rectangle R1;
R1.getdata ( );
R1.area ( );
R1.perimeter ( );
}
Example:-write class specifies for the following class
- The name of the class is triangle
- It has three private data members’ side1, side2 and angle. The data type of all the data
members is int .
- The class has the following function members
getdata( ) read values from screen
Area ( ) - calculates the area of the triangles
- The function members are public

#include<iostream.h>
Class triangle {
Private:
int side1 , side2, angle;

Page 22
Public:
Void getdata( )
{
Cout<<”\n enter the side of the triangle”;
Cin>>side1>>side2;
Cout<<”\n enter the include angle”;
Cin>>angle;
}
Void area ( )
{
Float A=0.5*side1*side2*sin (angle);
Cout<<”\n area<<”A;
}
};
Void main ( )
{
triangle T;
T.getdata ( );
T.area ( );
}
3- Implement inheritance
What is inheritance?
Inheritance is the process of creating new classes called derived classes from
existing classes.
- The derived class inherits all the capabilities of the base class but can add
requirements of its own
It has some advantage
- It permits code reusability
- Help in the conceptualization of a programming problem and in the overall design of
the syntax.
Inheritance syntax
We state inheritance in code by giving the name of the class as usual, but before the
opening branch of the class body, we put a colon and the name of the base class.
Class Base
{
.
.
};
Class Derived: Public Base
{
----------
}
Example
Class Counter
{

Page 23
Public:
int count;
Counter ( )
{
Counter=0;
}
int getcount ( )
{
Return count;
}
int incCount ( )
{
Count ++;
}
};
Class CountDn: Public Counter
{
Public:
Void decCount( )
{
Count --;
}
};
Void main ( )
{
Count Dc C1
Cout<< C1.getCount( );
C1.dec Count( );
Cout<<C1.getCount( );
}
Public and private inheritance
- Base class can be inherited publicly or privately.
- Access permission of the objects of the derived class depends on whether it is
derived publicly or privately.
- If the class is derived publicly objects of the derived class are able to access public
member functions of the base class.
- If the class is derived privately objects of the derived class cannot access public
members of the base class.

#include<iostream.h>
Class A
{
Private:
int X;
Protected:
int y;
Page 24
Public:
int Z;
};
Class B: public A
{
Public:
Void f ( )
{
int a;
a=x; // illegal
a=y; //legal
a=z; // legal
}
};
Class C: private A
{
Public:
Void f ( )
{
int a;
a=x; // illegal
a=y; //legal
a=z; // legal
}
};
Void main ( )
{
int a; B objB;
a=objB.x;//illegal
a=objB.y;//illegal
a=objB.z;//legal
Cobj C;
a=objC.x;//illegal
a=objC.y;//illegal
a=objC.z;//illegal
}

4- Use polymorphism at a simple level through inheritance to enable easy code


extension
Using operators or functions in different ways, depending on what they are operating on
is called polymorphism

Page 25
Self-Check EIS DBA4-LG05 M05 Apply basic OO principles in the target
LO2-SC02 language

Name: _________________________ Date: _______________

1- What is object?
2- What is object programming language?
3- What is class?
4- ______A member of a class it can only be assessed inside the class .we cannot use
outside the class
5- _____A member of a class it can be assessed both side and outside the class.

Page 26
Answer Key EIS DBA4-LG05 M05 Apply basic OO principles in the target
LO2-AK 02 language

1- Object is an entity that allows a programmer to encapsulate a type’s declaration a


long with declarations of operators to manipulate variables of that type.
2- Object –oriented programming is the use of objects and inheritance
3- Classes-is a collection of similar objects
4- Private
5- public

Page 27
Page 28
Information EIS DBA4-LG05 M05 LO3 – IS03 Debug code

1-Use An integrated development environment, particularly the language debugging


facilities

29
Visual Basic is fully fledged Object-Oriented Programming (OOP) Language.

Basic stands for Beginners All-purpose Symbolic Instruction Code.

The Integrated Development Environment of VB2010 Express the IDE Start Page consists of a
few sections, namely:

 The New Project/Open Project section.


 The Recent Projects section that shows a list of projects that have been created by you
recently.
 The Getting Started Pane- It provides some helpful tips to quickly develop your
applications.
 The Latest News section- It provides latest online news about Visual Basic 2010 Express.
It will announce new releases and updates
 The Properties section-let you defines the properties of each control

Starting new project

To start creating your first application, you need to click on new project; the new project dialog
box will appear

30
The dialog box offer you five types of project that you can create
o Window form Application(standard windows interface)
o WPF Application
o Console Application
o Class library
o WPF Browser Application
 You can create window applications; you will select Windows Forms Application. And
change the default name of the project for example MyFirstProgram. And click ok. The
following IDE Window will appear.
 It consists of an empty form, the toolbox tab, the menu bar, solution explorer and the
properties window.

 Form is the first place to build your Application. It is the place to design the user
interface.
 Solution explorer- displays a list of project, files and other components that you can
easily browse and access

31
 Prosperities window- set the properties of the objects in your application

Designing interface
 The first step is designing interface is design by adding controls to the form and set their
properties.
o Controls are objects that can be inserted into the form for various purposes. You
can write relevant code for them to perform certain tasks.
o The figure below shows the Toolbox that contains the controls. They are
categorized into Common Controls, Containers, Menus, Toolbars, Data,
Components, Printings and Dialogs. The most used common controls are Button,
Label, Combo Box, List Box, Picture Box and Textbox.

o
 To insert a control into the form, drag the control from the tool box (Ctrl + Alt + X) and
drop it into the form.

Using Control Properties window

32
 After adding a control to the default form, set certain properties for the control to
determine and customize the interface to the users, its appearance and how should it
behaves. You can set the properties of the controls in the properties window at design
time or at runtime.

Example:-Creating a simple program that displays a welcoming message

Properties Value
Name WelcomeMsg Frm
Back color Select a back ground color of your choice
Font Ms Sans Serif Size 10 and Bold
Fore color White ( the color of the displayed text
Maximize Box False ( cannot be maximized)
Text Visual Basic 2010

Next, Insert a label in to the form and set its properties as follows

Properties Value
Auto size False
Name Msglbl
Back color Click the drop down arrow and select a background color of your choice
Border style Fixed single
Font Ms sans serif size 10 and Bold
Fore color Black
Size 239,32
Text Blank it

33
Next, click on the form and enter the following code

Private sub WelComeMsg frm_Load(By Val Sender As System.Object, By Vale As


System.Event Args) Handles MyBase.Load

Msglbl.Text=” WELCOME TO VISUAL BASIC 2010”

End sub

Now press F5 to run the program

The output is

Writing the Code

The event Procedure

 Visual Basic is an object oriented and event driven programming language.


 Event driven means the user decides what actions to take, like clicking a command button
or entering text in a text box.

 An event is related to an object, it is an incident that happens to the object due to the


action of the user, such as clicking the mouse or depressing a key on the keyboard.

 Events are click, double-click , Drag drop , enter and more

Understanding the code structure of an event procedure

The structure of the code is

34
Private sub……..
Statements/code…..
End sub

There are several of the structures such as

i- Public sub
Enter your code here
End sub
ii- Sub
Enter your code here
End sub
iii- Function
Enter your code here
End function

Visual Basic Data types

Visual Basic classifies data into two major data types, the numeric data types and the non-
numeric data types.

Numeric Data Types


Numeric data types are data that consist of numbers that can be computed mathematically such
as add, minus, multiply, divide and soon.
It divided into 7 types, depending on the range of values they can store.

Non numeric Data Types

Numeric data types are data that cannot be manipulated mathematically using standard arithmetic
operators. The non-numeric data comprises text or string data types, the Date data types, the
Boolean data types that store only two values(true or false), Object data type and variant data
type.

35
Suffixes for Literals
Literals are values that you assign to a data
For example, we can use num=1.3089# for a double type data. Some of the suffixes are
displayed in Table

String literals within two quotations and date and time literals within two# sign. Strings can
contain any characters, including numbers. The following are few examples:
Member Name=”Turban,John”
TelNumber=”1800-900-888-777”
LastDay=#31-Dec-00#
ExpTime=#12:00am#

Managing Variables
Variables are areas allocated by the computer memory to hold data. Each variable must be given
a name. To name a variable in Visual Basic, you have to follow a set of rules.

Variable Names
The following are the rules when naming the variables in Visual Basic
 It must be less than 255 characters
 No spacing is allowed
 It must not begin with a number
 Period is not permitted

36
Examples of valid and invalid names are displayed in Tables

Declaring variables
 Declare the variables before using them by assigning names and data types. If you fail to
do so, the program will show an error.
 They are normally declared in the general section of the codes’ windows using the Dim
statement.

 The format is as follows:
Dim Variable Name As Data Type

Example
Private sub Form_Load(By Val Sender As System.Object, By Vale As System.Event Args)
Handles MyBase.Load
Dim password As String
Dim yourName As String
Dim firstnum As Integer
Dim secondnum As Integer
Dim total As Integer
Dim doDate As Date
End sub

 You may also combine them in one line, separating each variable with a comma, as
follows:
Dim password As String, yourName As String, firstnum As Integer …………..
 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 string, just use the same
formats as example 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,
Example
Dim yourName as string *10
yourName can holds no more than 10 characters

37
Assigning Values to Variables
After declaring various variables using the Dim statements, we can assign values to those
variables. The general format of an assignment is

Variable=Expression

The expression could be a mathematical expression, a number, a string, a Boolean value (true or
false) and etc.

The following are some examples:


firstNumber=100
seconNumber=firstNumber-99
userName=”John Lyan”
userpass.Text=password
Label1.Visible=True
Command1.Visible=false
Label4.Caption=textbox1.Text
thirdNumber=Val(usemum1.Text)
Total=firstNumber+secondNumber+ThirdNumber

Constants
Constants are different from variables in the sense that their values do not change during the
running of the program.

Declaring a constant
The format to declare a constant is
Const Constant Name AS Data type=Value

Example

Private Sub Form1_Load(ByVal sender As System.Object,ByVal e As


System.EventArgs)Handles MyBase.Load
Const Pi As Single=3.142
Const Temp As Single=37
Const Score As Single=100
End sub

Mathematical Operations

In Visual Basic, we can write code to instruct the computer to perform mathematical operations
such as addition, subtraction, multiplication, division and more. To write code for mathematical
operations, we use various arithmetic operators. The Visual Basic arithmetic operators are very
similar to the normal arithmetic operators. The lists of arithmetic operators are shown in table
below:

38
String Manipulation

Generally we have to deal with two types of data, the numeric and the non-numeric data types.
The non-numeric data again divided in to a few types, the most common one being text, or
string. Examples of string are words, sentences, names, addresses, gender, cities, book titles and
many more.

String Manipulation Using + and & signs.

In Visual Basic, Strings can be manipulated using the & sign and the + sign, both perform the
string concatenation which by combining two or more smaller strings into larger strings. For
example, we can join “Visual” and “Basic” into “Visual Basic” using “Visual”&”Basic” or
“Visual “+”Basic”, as shown in the example below

Example
Private Sub Button1_Click (ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
Dim text1, text2, text3 As String
text1 = “Visual”
text2 = “Basic”
text3 = text1 + text2
Label1.Text = text3
End Sub

 The line text3=text1+text2 can be replace by text3=Text& text2 and produce the same
output.However, if one of the variables is declared as numeric data types, you cannot use
the + sign, you can only use the & sign.

Example
Dim text1, text3 As String
Dim text2 As Integer
text1 = “Visual”
text2 = 22
text3 = text1 + text2
Label1.Text = text3

39
 This code will produce an error because of data mismatch. However, using & instead of +
will be all right.

Dim text1, text3 As String


Dim text2 As Integer
text1 = “Visual”
text2 = 22
text3 = text1 & text2
Label1.Text = text3
 You can combine more than two strings to form a larger string, like the following
example:

Public Class Form 1


Private Sub Button1_Click (ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
Dim text1, text2, text3, text4, text5, text6 As String
text1 = “Welcome”
text2 = “to”
Text3= “Visual”
Text4 = “Basic”
Text5= 2010
Text6= text1 + text2+text3+text4&text5
Label1.Text = text6
End sub
End class
Running the above program will produce the following screen shot

Controlling program flow

Visual Basic code that can make decisions, it will process input from the user and control the
program flow and outcomes based on the decisions.

Decisions making is an important part of programming because it can solve practical problems
intelligently and provide useful output to the user. For examples, we can write a VB program that
can ask the computer to perform certain task until a certain condition is met, or a program that
will reject non-numeric data. In order to control the program flow and to make decisions, we will
introduce the If…Then…Else control structure. To write VB code that involves If…Then…Else,
we need to use the conditional operators and the logical operators.

40
Conditional operators

The conditional operators are powerful tools that resemble mathematical operators. These
operators allow comparing data values and then deciding what actions to take, whether to
execute a program or terminate the program and more. These operators are typically used to
compare two values to see whether they are equal, one value is greater than or less than the other
value. The comparison will return a true or false result. These operators are shown in tables.

Logical operators

Sometimes we might need to make more than one comparison before a decision can be made and
an action taken. In this case, using numerical comparison operators alone is not sufficient; we
need to use additional operators known as the logical operators. The logical operators are shown
in table

Using the If control structure with comparison operators

To effectively control the visual basic program flow, we shall use the If control structure together
with the conditional operators and logical operators. There are basically three types of If control
structures, namely

 If…….Then statement
 If …….Then…..Else statements and

 If……..Then…..ElseIf statement

41
If…….Then statement

This is the simplest control structure, to perform a certain action specified by the Visual Basic
expression if the condition is true. However, when the condition is false, no action will be
performed.

The general format for the If….. Then...Statement is

If condition Then
Visual Basic 2010 expression
End if

Example

Private Sub Button1_Click (ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click

Dim myNumber As Integer


myNumber=Textbox1.Text
If myNumber>100 Then
Label2.Text=”You win a lucky prize”
End if
End sub
 When you run the program and enter a number that is greater than 100, you will see the
“you win a lucky prize” statement. On the other hand, if the number entered is less than
or equal to 100, you don’t see any display.

If……Then……Else statement

If …… then statement is not very useful in programming and it does not provide choices for the
user. Perform a certain action specified by the visual Basic expression if the condition is true.
And when the condition is false, an alternative action will be executed.

The general format for the If……Then…..Else a statement is

If condition Then
Visual Basic 2010 expression
Else
Visual Basic 2010 expression

End if

42
Example

Private Sub Button1_Click (ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click

Dim myNumber As Integer


myNumber=Textbox1.Text
If myNumber>100 Then
Label2.Text=” Congratulation! You win a lucky prize”
Else
Label2.Text=”Sorry, You did not win any prize”
End if
End sub
 When you run the program and enter a number that is greater than 100, the statement
“Congratulation! You win a lucky prize” will be show. On the other hand, if the number
entered is less than or equal to 100, you will see the “Sorry, you did not win any
prize”statement

Example

Private Sub Button1_Click (ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click

Dim myNumber , MyAge As Integer


myNumber=Textbox1.Text
MyAge= Textbox2.Text
If myNumber>100 and MyAge>60 Then
Label2.Text=” Congratulation! You win a lucky prize”
Else
Label2.Text=”Sorry, You did not win any prize”
End if
End sub
 This program use the logical and And operator beside the conditional operators. This
means that both the conditions must be fulfilled in order for the conditions to be true,
otherwise the second block of code will be executed. In this example, the number entered
must be more than 100 and the age must be more than 60 in order to win a lucky prize,
any one of the above conditions not fulfilled will disqualify the user from winning a
prize.

If…..Then….ElseIf statement

If there are more than two alternative choices, using just if…..Then…Else statement will not be
enough. In order to provide more choices, we can use the If...Then….ElseIf statement executed.

The general format for the if….Then…Else statement is

If condition Then
Visual Basic 2010 expression

43
Elseif condition Then
Visual Basic 2010 expression
Elseif condition Then
Visual Basic 2010 expression
.
.
Else
Visual Basic 2010 expression
End if

Example

Private Sub Button1_Click (ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click

Dim Mark As Integer


Dim Grade As String
Mark=TextBox1.Text
If myNumber>=80 Then
Grade=”A”
ElseIf Mark>=60 and Mark<80 then
Grade=”B”
ElseIf Mark>=40 and Mark<60 then
Grade=”C”
Else
Geade =”D”
End if
End sub

Using Select Case control structure

Select Case control structure is slightly different from the If….Else…Then control structure. The
difference is that the Select Case control structure typically only makes decision on one
expression. On the other hand, the If …Then…Else statement control structure may evaluate
only one expression, or it may also compute entirely different dimensions. Select Case is
preferred when there exist multiple conditions.

The Select Case…End Select Structure

The syntax of the Select Case control structure is as follows:


Select Case test expression
Case expression list 1
Block of one or more Visual Basic statements
Case expression list 2
Block of one or more Visual Basic Statements
Case expression list 3
Block of one or more Visual Basic statements

44
Case expression list 4
.
.
.
Case Else
Block of one or more Visual Basic Statements
End Select

Example

Private Sub Button1_Click (ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click

‘Examination Marks
Dim Mark As Single
Mark=mrk.text
Select case Mark
Case 0 to 49
Label1.Text=”Need to work harder”
Case 50 to 59
Label2.Text=”Average”
Case 60 to 69
Label3.Text=”Above Average”
Case 70 to 84
Label4.Text=”Good”
Case Else
Label5.Text=”Excellent”
End select
End sub

Example

In this example, you can use the keyword Is together with the comparison operators.

Private Sub Button1_Click (ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click

‘Examination Marks
Dim Mark As Single
Mark=mrk.text
Select case Mark
Case Is >=85
Label1.Text=”Excellent”
Case Is>= 70
Label2.Text=”Good”
Case Is>=60
Label3.Text=”Above Average”
Case Is>=50

45
Label4.Text=”Average”
Case Else
Label5.Text=”Need to work harder”
End select
End sub

Looping
In VB programming, a sequence of instructions that is repeated until a certain condition is met is
called looping.  
In Visual Basic, we have three types of Loops, they are
 The For…..Next loop,
 The Do loop. And
 The While…..End while loop

Looping using the For….Next Loop

The syntax for looping using the For…Next loop is:


For counter=startNumber to endNumber(step increment)
One or more Visual Basic statements
Next
To exit a For…..Next Loop, you can place the Exit For statement within the loop; and it is
typically used together with the If….Then…..statement.

Example
Dim counter as Integer
For counter=1 to 10
ListBox1.Items.Add (counter)
Next
 The program will enter number 1 to 10 in to the list box.
Example

Dim counter, sum As Integer


For counter=1 to 100 step 10
Sum+=counter
ListBox1.Items.Add (sum)
Next
 The program will calculate the sum of the number as follows: sum=0+10+20+30+40+…
Example
Dim counter, sum as Integer
Sum=1000
For counter=100 to 5 step -5
Sum- =counter
ListBox1.Items.Add (sum)
Next
 Notice that increment can be negative. The program will compute the subtraction as
follows: 1000-100=95-90…….

46
Example

Dim n as integer
For n=1 to 10
If n>6 then
Exit for
End if
Else
ListBox1.Items.Add (n)
Next
End if
Next
 The process will stop when n is greater than 6

Do Loop

The formats are

a) Do while condition
Block of one or more VB statements
Loop
b) Do
Block of one or more VB statements
Loop while condition
c) Do until condition
Block of one or more VB statements
Loop
d) Do
Block of one or more VB statements
Loop until condition
Exiting the loop- sometime we need exit to exit a loop prematurely because of a certain
condition is fulfilled.
The syntax to use is known as Exit Do.
Example
Do while counter<=1000
TextBox1.Text=counter
Counter+=1
Loop
 The above example will keep on adding untile counter>1000
 The above example can be rewritten as
Do
Textbox1.Text=counter
Counter+=1
Loop until counter>1000

47
While…End while loop

Structure of a while….End while is very similar to the Do loop.

Format while condition


Statements
End while
Example

Dim sum, n as Integer

Private Sub Button1_Click (ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click

Dim sum, n as Integer


While n<> 100
n+=1
sum=sum+n
Listbox1.Items.Add (n&VbTab&sum)
End while
End sub

Functions

A VB function is a type of procedure that returns a value which is passed on to the main
procedure to finish the execution. The main purpose of the function is to accept a certain Input
and return values; which is passed on to the main program to finish the execution.
There are two types of functions in Visual Basic, the built-in functions (internal) and the
functions created by the programmers.

The general syntax of a function is

Function Name (arguments)

The arguments are values that are passed on to the function.


There are two very basic built-in functions of Visual Basic, i.e. the MsgBox( ) and the InputBox
( ) functions.

MsgBox ( ) Function

The objective of MsgBox is to produce a pop-up message box and prompts the user to click on a
command button before he or she can continues.

This syntax is as follows:

yourMsg=MsgBox(Prompt, Style Value, Title)

48
The first argument, Prompt, will display the message in the message box. The Style Value will
determine what type of command buttons appear on the message box, The Title argument will
display the title of the message board.

Example
yourMsg=Msg(“Click OK to proceed”,1,”startup Menu”) and
yourMsg=Msg(“Click Ok to Proceed”. VbOKCancel,”startup Menu”) are the same.
 yourMsg is a variable that holds values that are returned by the MSgBox() function.

The corresponding named constant and buttons

Examples

Private Sub Button1_Click (ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click

Dim testmsg As Integer


Testmsg=MsgBox(“click to test”,1,”Test message”)
If testmsg=1 then
messageBox.show(“you have clicked the Ok button”)
Else
messageBox.show(“you have clicked the cancel button”)

49
End if
End sub
 To make the message box looks more sophisticated, you can add an icon besides the
message.
 There are four types of Icons available in Visual basic

Examples

Private Sub Button1_Click (ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click

Dim testmsg As Integer


Testmsg=MsgBox(“click to test”,VbYesNCancel+VbExclamation,”Test message”)
If testmsg=6 then
MessageBox.show(“you have clicked the Yes button”)
Elseif testmsg=7 then
MessageBox.show(“you have clicked the No button”)
Else
MessageBox.show(“you have clicked the Cancel button”)
End if
End sub

The output of this example

50
The InputBox( ) Function

An InputBox( ) function will display a message box where the user can enter a value or a
message in the form of text.

The syntax to call up an Input Box is

Usermsg=Microsoft.VisualBasic.InputBox(Prompt, Title, default_text, x-position, y-position)


 Usermsg- is avariant data type but typically it is declared as string which accepts the
message input by the user.
 Prompt- the message displayed normally as a question asked
 Title- the title of the input box
 Default-text- the text that appears in the input field where the user may change the
message according to his or her wish
 X-position and Y-position- the position or the coordinate of the input box

Example

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click
Dim userMsg As String
userMsg = Microsoft.VisualBasic.InputBox(“What is your message?”, “Message Entry Form”,
“Enter your messge here”, 500, 700)
If userMsg <> “” Then
MessageBox.Show(userMsg)
Else
MessageBox.Show(“No Message”)
End If
End Sub

The input box will appear as shown in the figure below when you press the command
button

String function

The main purpose of a function is to accept an input and return a value. The value then is passed
on the main program to finish.

51
The Mid function- is to retrieve apart of text from a given phrase.

The format of the Mid function is


Mid (phrase, position, n)
 Phrase- is the string from which apart of text is to be received
 Position- is starting position of the phrase from which is the retrieving process begins
 N – is the number of characters to retrieve
Example
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
Dim myphrase As String
myphrase = Microsoft.VisualBasic.InputBox(“Enter your phrase”)
Label1.text=Mid(Myphrase,2,6)
End sub
Out put

The Len function:-the length function returns an integer value equals to the length of a
phrase or a sentence, including the empty spaces

The syntax is Len (“Phrase”)

Example

Len(Visual basic)=12 and Len(welcome to VB tutorial)=22


Example

Public class form1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click
Label1.text=Len (TextBox1.text)
End sub
End class

52
Out put

The Right functions:-extracts the right position of a phrase.

The syntax:- Microsoft.Visua;Basic.Right(“phtase”,n)

 Where n is the starting position from the right of the phrase where the portion of the
phrase is going to be extracted

Example

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click
Dim text1 As String
Text1=Textbox1.text
Label1.text=Microsoft.Visua;Basic.Right(text1,4)
End sub
Out put

The left function: - :-extracts the left position of a phrase

The syntax: - Microsoft.Visua;Basic.left(“phrase”,n)

 Where n is the starting position from the left of the phrase where the portion of the phrase
is going to be extracted

53
Example

Microsoft.Visua;Basic.left(“Visual Basic”,4)=Visu

The Trim function;- empty spaces on both side of the phrase

The syntax: - Trim (“phrase”)

Example

Trim (“Visual Basic”)= Visual Basic


 There are two trim functions
 The Ltrim:- left portion space syntax Ltrim(“phrase”)
Example LTrim (“ Visual Basic”) = Visual Basic
 TheRLtrim:- right portion space syntax Rtrim(“phrase”)
Example RTrim (“Visual Basic ”) = Visual Basic

The Ucase and Lcase function: - upper case and lower case function

Syntax: Microsoft.Visua;Basic.Ucase(“phrase)
Microsoft.Visua;Basic.Lcase(“phrase)
Example Microsoft.Visua;Basic.Ucase(“Visual Basic”)=VISUAL BASIC
Microsoft.Visua;Basic.Lcase(“Visual Basic”)=visual basic

The Math Functions

Math functions in VB programming are functions that process one or more numbers and return a
value. They are no different functions in mathematics. Though we can create customized math
functions,   they are Abs, Exp, Fix, int, Log. Rnd(), Round and the trigonometric function .

The Abs function

The Abs function returns the absolute value of a given number.


The syntax is Math. Abs (number)
 The Math keyword here indicates that the Abs functions belong to the Math class.
However, not all math functions belong to the Math class.

The Exp Function

The Exp of a number is the exponent value of X , i.e ex ,for example, Exp(1)=e=2.71828182

The syntax is Math.Exp(number)

Example

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click

54
Dim Num1, Num2 As String
Num1=textBox1.text
Num2=Math.Exp(Num1)
Label1.Text=Num2
End sub

The Fix function

The Fix function truncates the decimal part of a positive number and returns the largest integer
smaller than the number. However, when the number is negative, it will return the smallest
integer larger than the number .For example, Fix (9.2) but Fix (-9.4) =-9

Example

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click
Dim Num1, Num2 As String
Num1=textBox1.text
Num2=Fix (Num1)
Label1.Text=Num2
End sub

The Int function

The Int is a function that converts a number in to an integer by truncating its decimal part and the
resulting integer is the largest integer that is smaller than the number. For example Int(2.4)=2,
Int(6.9)=6 Int(-5.7)=-6, Int(-99.8)=-100

The Log Function

The Log Function is the function that returns the natural logarithm of a number, For example,
Log (10) =2.302585
Example

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click
Dim Num1, Num2 As String
Num1=textBox1.text
Num2=Math.Log (Num1)
Label1.Text=Num2
End sub

The Rnd( ) Function

The Rnd function returns a random value between 0 and 1; Random numbers often need to be
converted in to integers in programming. For example ,if we wish to obtain a random output of 6

55
integers random from 1 to 6 , which makes the program behaves like a virtual dice, we need to
convert the random numbers to integers using the formula Int(Rnd*6)+1.

Example

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click
Dim Num As Integer
Randomize( )
Num= Int(Rnd( )*6)+1
Label1.Text=Num
End sub
 In this example, Int(Rnd*6)will generate a random integer between 0 and 5 because the
function Int truncates the decimal part of the random number and returns an integer. After
adding 1, you will get a random number between 1, and 6 every time you click the
command button. for example, let say the random number generated is 0.96, after
multiplying it by 6, it becomes 5.88, and using the integer function Int(5.88)will convert
the number to 5; and after adding 1 you will get 6.

The Round function

The Round function rounds up a number to a certain number of decimal places.


The syntax is Round (n.m) which means to round a number n to m decimal places. For example,
Math,Round(7.2567,2)=7.26

Example

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click
Dim Num1, Num2 As String
Num1=textBox1.text
Num2=Math.Round (Num1,2)
Label1.Text=Num2
End sub
 The Math keyword indicates that the Round function belongs to the math class

The Sqrt Function: - returns the square root of a number

Example Sqrt(400) will returns a value of 20.

C=math.sqrt(a^2+b^2)

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click
Dim a,b,c As single

a=val(txtA.text)

56
b=val(txtB.text)
C=math.sqrt(a^2+b^2)
lblC.text=C.ToString(“F”)
End sub

The Format Function

The Format function in Visual Basic displays the numeric values in different forms. There are
two types of Format functions in Visual Basic; one of them is the built-in format function while
another one is defined by the users.

(i) The syntax of a built-in Format function is

Format (n, “style argument”)

Where n is a number.

List of style arguments

Style argument Explanation Example

General To display the number without having Format(8972.234, “General


Number separators between thousands Number”)=8972.234
To display the number without having
Fixed separators between thousands and rounds it up Format(8972.2,
to two decimal places. “Fixed”)=8972.23

Standard To display the number with separators or Format(6648972.265,


separators between thousands and rounds it up “Standard”)= 6,648,972.27
to two decimal places.

Currency To display the number with the dollar sign in Format(6648972.265,


front, has separators between thousands as well “Currency”)= $6,648,972.27
as rounding it up to two decimal places

Percent Converts the number to the percentage form Format(0.56324,


and displays a % sign and rounds it up to two “Percent”)=56.32 %
decimal places.

Example 15.1

Private Sub Button1_Click (ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click, Button5.Click, Button4.Click, Button3.Click
Label1.Text = Format (8972.234, “General Number”)

57
Label2.Text = Format(8972.2, “Fixed”)
Label3.Text = Format(6648972.265, “Standard”)
Label4.Text = Format(6648972.265, “Currency”)
Label5.Text = Format(0.56324, “Percent”)
End Sub

The Output is shown below:

(ii) The syntax of the user-defined Format Function is

Format (n, “user’s format”)

Although it is known as user-defined format, we still need to follow certain formatting styles.

Example

Private Sub Button1_Click (ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click, Button5.Click, Button4.Click, Button3.Click

58
Label1.Text = Format (8972.234, “0.0”)
Label2.Text = Format(8972.2345, “0.00”)
Label3.Text = Format(6648972.265, “#,##0.00”)
Label4.Text = Format(6648972.265, “$#,##0.00”)
Label5.Text = Format(0.56324, “0%”)
End Sub

The Output is shown below:

Formatting Date and Time

In Visual Basic, date and time can be formatted using predefined formats and also user-defined
formats

Formatting Date and time using predefined formats

 Instead of “General date”, you can also use the abbreviated format “G”, i.e. Format
(Now, “G”). And for “Long Time”, you can use the abbreviated format “T”. As for
“Short Time”, you may use the abbreviated format “t”

Example

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click
Label1.Text = Format(Now, “General Date”)

59
Label2.Text = Format(Now, “Long Date”)
Label3.Text = Format(Now, “short Date”)
Label4.Text = Format(Now, “Long Time”)
Label5.Text = Format(Now, “Short Time”)
End Sub

The output is shown in the diagram below:

Formatting Date and time using user-defined formats

The syntax of a user-defined for date /time is

Format (expression style)

Example

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click
Label1.Text = Format(Now, “M”)

60
Label2.Text = Format(Now, “MM”)
Label3.Text = Format(Now, “MMM”)
Label4.Text = Format(Now, “MMMM”)
Label5.Text = Format(Now, “dd/MM/yyyy”)
Label6.Text = Format(Now, “MMM,d,yyyy”)
Label7.Text = Format(Now, ”h:mm:ss tt”)
Label8.Text = Format(Now, ”MM/dd/yyyy h:mm:ss tt”)
End Sub

The output is shown in the diagram below:

Using Advanced control

Advanced control in VB are check box, Radio button, List box and combo box.

The Check Box

A Check box allows the user to select one or more items by checking the check box/check boxes
concerned.

Example

In Visual Basic, you may create a shopping cart. The user can click on check boxes on the
shopping cart that correspond to the items they intend to buy, where the total payment can be
computed at the same time.

Private sub BtnCalculate_click (ByVal sender As System.Object, ByVal e As


System.EventArgs) HandlesBtnCalculate.Click

Const LX As Integer=100
Const BN As Integer=500
Const SD As Integer=200
Const HD As Integer=80
Const HM As Integer=300
Const AM As Integer=150
Dim sum As Integer

61
If CheckBox1.checked=True then
Sum+=LX
End if
If CheckBox2.checked=True then
Sum+=BN
End if
If CheckBox3.checked=True then
Sum+=SD
End if
If CheckBox4.checked=True then
Sum+=HD
End if
If CheckBox5.checked=True then
Sum+=HM
End if
If CheckBox6.checked=True then
Sum+=AM
End if
Label 5.Text=sum.tostring(“C”)
End sub

Out put

Using Radio Button

The radio button is another control in Visual Basic that allows selection of choices. However, it
operates differently from the check box. While the check boxes allow the user to select one or
more items, radio buttons are mutually exclusive, which means the user, can only choose one
item only out of a number of choices.

Example: - which allows the user to select one color only.


The code
Dim Strcolor As String

62
Private sub RadioButton1.checkedChanged (ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles RadioButton1. checkedChanged
Strcolor=”Red”
End sub
Private sub RadioButton2.checkedChanged (ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles RadioButton2. checkedChanged
Strcolor=”Green”
End sub
Private sub RadioButton3.checkedChanged (ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles RadioButton3. checkedChanged
Strcolor=”Yellow”
End sub
Private sub Button1_click (ByVal sender As System.Object, ByVal e As System.EventArgs)
HandlesButton1.Click
Label 2.Text= Strcolor
End sub

Out put

Using List Box

A list box is an object that displays a list of items. You can populate the list box with items at
design time or at runtime. You can also remove the items from the list box. You can also clear an
item from the list box based on its index, starting from 0.

Example

Start a new project and name it as MylistBox. Change the Form1 text to Name list. Insert a list
box in to the form and change its name to myNameList in the property window.Next,add two
buttons to form1, name the first one as BtnAdd and change the text to Add Name, Name the first
one as BtnRemove and change its text to Remove Name.

Adding items to the List Box at Design Time

Go to properties window of the List Box and Scroll to find the items property. On the left of the
items property, you can see the word Collection with a three-dot button on the right.

63
Now click on three-dot button to go in to the string collection Editor. Now you can add items to
the list, one item per line. Here we add a list of ten names.

Press F5 to run the program and you can see the list of names entered earlier by clicking the drop
down arrow of the combo box.

Adding items to the List Box at Run time

To add an item to the List Box at runtime, use the following code:
Listbox.Items.Add(“Name”)

In our example, you can add the name “Aster, using the following statement.
MyNameList.Items.Add(“Aster”)

When you run the program and click the add name button, the name Aster will be added to the
end of the list.
 You can also let the user add items to the list box via an input box. Place the following
code under the BtnAdd_click procedure.
Dim userMsg As String
userMsg=Microsoft.VisualBasic.InputBox(“Enter a name and Click Ok”,
”Names Entry form”,”Enter name here”, 100,200)
myName:List.Items.Add(userMsg)

64
When you run the program and click the Add Name button, the input box is shown, and you can
then enter a name and click the ok button

Removing and clearing items from the List Box

To remove items from the list in the list box, we use the Remove ( ) method
The syntax using our example is:
ListBox.Items.Remove(“ItemName”)
Referring to our example,you can remove the name Biruk using the following statements:
myNameList.Items.Remove(“Biruk”)
To remove an item according to its index, we need to use the RemoveAt( ) method.
The syntax is:
ListBox.Items.RemoveAt(“Index”)
Referring to our previous example, we can remove the second name using the following syntax:
myNameList.Items.RemoveAt(1)
To remove a selected item, we can use the following syntax:
If NameList.SelectedIndex< >-1 Then
myNameList.Items.RemoveAt(NameList.selectedIndex)
End if

Using Combo Box

Combo Box is a kind of list box but it does not display all the items at one time. Instead, it
displays one items at a time and provides a drop-down list where the user and click and view the
other items. The advantage of using combo box is it saves spaces.

Example

Start a new project and name it as MyComboBox. Change the Form1 text to ACollection of
Names. Insert a Combo box in to the form and change its name to NameList in the property
window.Next,add two buttons to form1, name the first one as BtnAdd and change the text to
Add Name, Name the first one as BtnRemove and change its text to Remove Name.

Adding items to the List Box at Design Time

Go to properties window of the Combo Box and Scroll to find the items property. On the left of
the items property, you can see the word Collection with a three-dot button on the right.

Now click on three-dot button to go in to the string collection Editor. Now you can add items to
the list, one item per line. Here we add a list of ten names.

65
Press F5 to run the program and you can see the list of names entered earlier by clicking the drop
down arrow of the combo box.

Adding items to the Combo Box at Run time

To add an item to the Combo Box at runtime, use the following code:
Cpmbobox.Items.Add(“Name”)

In our example, you can add the name “Aster, using the following statement.
NameList.Items.Add(“Aster”)

When you run the program and click the add name button, the name Aster will be added to the
end of the list.
 You can also let the user add items to the list box via an input box. Place the following
code under the BtnAdd_click procedure.
Dim userMsg As String
userMsg=Microsoft.VisualBasic.InputBox(“Enter a name and Click Ok”,
”Names Entry form”,”Enter name here”, 100,200)
Name:List.Items.Add(userMsg)
When you run the program and click the Add Name button, the input box is shown, and you can
then enter a name and click the ok button

66
Removing and clearing items from the Combo Box

To remove items from the list in the combo box, we use the Remove ( ) method
The syntax using our example is:
ComboBox.Items.Remove(“ItemName”)
Referring to our example,you can remove the name Biruk using the following statements:
NameList.Items.Remove(“Biruk”)
To remove an item according to its index, we need to use the RemoveAt( ) method.
The syntax is:
ComboBox.Items.RemoveAt(“Index”)
Referring to our previous example, we can remove the second name using the following syntax:
NameList.Items.RemoveAt(1)
To remove a selected item, we can use the following syntax:
If NameList.SelectedIndex< >-1 Then
NameList.Items.RemoveAt(NameList.selectedIndex)
End if
2-Use detects and resolve errors program debugging techniques

Errors Handling

Error handling is an essential procedure in Visual Basic programming that helps make a program error-
free. An error-free program can run smoothly and efficiently, and the user does not have to face all sorts
of problems such as program crashes or system hangs.

Errors often occur due to incorrect input from the user. For example, the user might make the mistake of
attempting to enter text (string) to a box that is designed to handle only numeric values such as the weight
of a person, the computer will not be able to perform arithmetic calculation for text therefore will create
an error. These errors are known as synchronous errors.

Therefore a good programmer should be more alert to the parts of program that could trigger errors and
should write errors handling code to help the user in managing the errors. Writing errors handling code is
a good practice for Visual Basic programmers, so do not try to finish a program fast by omitting the errors
handling code. On the other hand, there should not be too many errors handling code in the program as it
create problems for the programmer to maintain and troubleshoot the program later. VB has improved a
lot in its built-in errors handling capabilities compared to older version versions of VB. For example,
when the user attempts to divide a number by zero, Vb will not return an error message but gives the
‘infinity’ as the answer (although this is mathematically incorrect, because it should be undefined)

Using On Error GoTo Syantax

67
Example Division by Zero

In this example, we will deal with the error of entering non-numeric data into the textboxes that suppose
to hold numeric values. The program label here is error_hanldler. When the user enter a non-numeric
values into the textboxes, the error message will display the text “One of the entries is not a number! Try
again!” If no error occurs, it will display the correct answer. Try it out yourself.

The Code

Public Class Form1

Private Sub CmdCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

Handles CmdCalculate.Click

Lbl_ErrorMsg.Visible = False
Dim firstNum, secondNum As Double
On Error GoTo error_handler
firstNum = Txt_FirstNumber.Text
secondNum = Txt_SecondNumber.Text
Lbl_Answer.Text = firstNum / secondNum
Exit Sub 'To prevent error handling even the inputs are valid
error_handler:
Lbl_Answer.Text = "Error"
Lbl_ErrorMsg.Visible = True
Lbl_ErrorMsg.Text = “One of the entries is not a number! Try again!"
End Sub
End Class

Out Put

Errors handling using try…..Catch….End Try Structure

68
VB has adopted a new approach in handling errors known as exceptions handling. It is supposed to be
more efficient than the old On Error Goto method, where it can handles various types of errors within the
Try…Catch…End Try structure.

The structure looks like this


Try
Statements
Catch exception_variable as Exception
Statements to deal with exceptions
End Try

Example

This is a modification of the previous Example Instead of using On Error GoTo method, we use the
Try…Catch…End Try method. In this example, the Catch statement will catch the exception when the
user enters a non-numeric data and return the error message. If there is no exception, there will not any
action from the Catch statement and the program returns the correct answer.

The code
Public Class Form1
Private Sub CmdCalculate_Click(ByVal sender As System.Object, ByVal eAs System.EventArgs)
Handles CmdCalculate.Click
Lbl_ErrorMsg.Visible = False
Dim firstNum, secondNum, answer As Double
Try
firstNum = Txt_FirstNumber.Text
secondNum = Txt_SecondNumber.Text
answer = firstNum / secondNum
Lbl_Answer.Text = answer
Catch ex As Exception
Lbl_Answer.Text = "Error"
Lbl_ErrorMsg.Visible = True
Lbl_ErrorMsg.Text = " One of the entries is not a number! Try again!"
End Try
End Sub
End Class

Out Put

69
Self-Check EIS DBA4-
Debug Code
LG05 M05 LO3-SC03

70
Name: _________________________ Date: _______________

1- Basic stands for?

2- What is the section of Integrated Development Environment of VB?

3-Mention at least 5 most common controls are?


4-what are VB Events?
5-What are the two types of data type in Visual Basic?
6-What are non-numeric data types in VB?
7- What are the rules when naming the variables in Visual Basic?
8- What are the two types of function in VB?
9- Maintion at least 5 string function?
10- What is Error handling

71
Answer Key EIS DBA4-LG05 M05
LO3-AK 03 Debug Code

1- Basic stands for Beginners All-purpose Symbolic Instruction Code.

2- The Integrated Development Environment of VB2010 Express the IDE Start Page consists of
a few sections, namely:

 The New Project/Open Project section.


 The Recent Projects section.
 The Getting Started Pane.
 The Latest News section
 The Properties section

3-The most used common controls are Button, Label, Combo Box, List Box, Picture Box and
Textbox.

4- VB Events are click, double-click, Drag drop, enter etc


5- The two major data types of VB, the numeric data types and the non-numeric data types.
6-Non-numeric data types in VB, the Date data types, the Boolean data types, Object data type
and variant data type.
7- The rules when naming the variables in Visual Basic
 It must be less than 255 characters
 No spacing is allowed
 It must not begin with a number
 Period is not permitted
8- The two functions are the built-in functions (internal) and the functions created by the
programmers.
9-String function are Mid functi function, Len function ,Righ function, Left function and Trim
Function
10- Error handling is an essential procedure in Visual Basic programming that helps make a program
error-free.

72
Information EIS DBA4-LG05 M05 LO4 – IS04
Document Activities

1-Follow Guidelines for developing maintainable code adhering to a set of coding


standard

Reading and writing Files

To be able to open a file and read the data from storage unit of a computer, such as a hard drive
as well as able to save the data in to the storage unit are important functions of the computer
program. In fact, the ability to store, retrieve and modify data makes a computer a power full tool
in database management.
 Using text file is an easy way to manage data
 VB allows the user to create a text file, save the text file as well as read text file, it is
relatively easy to write code for the above purpose in VB.
 Reading and writing to a text file in VB requires the use of the StreamReader class and
the streamWriter class respectively.
 StreamReader is a tool that enables the streaming of data by moving it from one location
to another so that the user can read it.
 StreamWriter is a tool that can write data input by the user to a storage device such as the
hard disk.

Reading a Text File

 To read file from hard disk or any storage we use the StreamReader class. To achieve that
first we include the following statements in the program code.
Imports System.IO
 We can declare a variable of the StreamReader data type
Dim FileReader As StreamReader
 If we don’t include the imports System.IO we have to use the statement
Dim FileReader As IO.StreamReader
Example: - start a new project and name it TxtEditor. Now insert the openFileDialog control in
to the form. The openFileDialog control returns a DialogResult value that can determine whether
the user clicks the OK button or Cancel button. Also insert a command button and change its
displayed text to “Open’ and name it as “BtnOpen”.next insert the textbox, name it TxtEditor
and set its multiline property to true.
Code
Imports System.IO
Pubic class Form1
Private Sub Button1_Click (ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click

73
Dim FileReader As StreamReader
Dim Results as DialiogResult
Results=OpenFileDialog1.ShowDialog
If Results=DialogResult.OK Then
FileReader=New SreamReader(openFileDialog1.FileName)
TxtEditor.Text=FileReader.ReadToEnd( )
FileReader.Close( )
End If
End sub

The Design Interface is

The open dialog box

Writing to a Text File


Writing a text file means storing the text entered by the user Via the textbox in to a storage
device such as hard drive. It also means saving the file. To develop this we use StreamWriter
class. And we need to insert the SaveFileDialog control in to the form as it is used to save the
data in to the storage device like a hard drive.we also insert another button and name it as

74
BtnSave. The code is the same as the code for reading the file; you just change the StreamReader
to StreamWriter and the method for ReadToEnd toWeite.

The code
Imports System.IO
Pubic class Form1
Private Sub Button1_Click (ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
Dim FileWriter As StreamWriter
Dim Results as DialiogResult
Results=SaveFileDialog1.ShowDialog
If Results=DialogResult.OK Then
FileWriter=New SreamWriter(SaveFileDialog1.FileName,False)
FileWriter.Write(TxtEditor.Text)
FileWrite.Close( )
End If
End sub

Output of interface

When you click the save button, the program will prompt you to key in the file name and the text
will be save as a text file. Finally, you can combine the two programs together and create a text
editor that can read and write text files

75
Adding Menu and Toolbar

Menus and toolbars are standard features of all windows applications despite the development of
more sophisticated GUI. The menu bar contains menus, which contain groups of menu items that
the user can used to execute certain commands to perform certain tasks like opening a file,
saving a file, printing a page, formatting a page and more.
On the other hand, a standard tool bar displays icons that can be used to open a file, save a file,
viewing a document, printing a document and more.

Adding menu

First, drag the menu strip and position it at the top part of the form. Add the first top-level menu
by typing it in the text that appears with a blurred text “type here”. The first menu you will add is
File, but you type it with the ampersand sign in front, like this &File. The reason is the
ampersand sign will underline the letter F, File at run time so that the user can use the keyboard
short-cut keys to execute a command. And you use the same procedure for other menus.

Writing code for the Menu Items

76
 The code of open is the same as reading file code now double click on the Open menu
item and enter the code.

Private Sub OpenToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles OpenToolStripMenuItem.Click
Dim Results as DialiogResult
Results=OpenFileDialog1.ShowDialog
If Results=DialogResult.OK Then
FileReader=New SreamReader(openFileDialog1.FileName)
TxtEditor.Text=FileReader.ReadToEnd( )
FileReader.Close( )
End If
End Sub
 The code of save menu is the same as writing file, now double click on the Save menu
items and enter the code
Private Sub SaveToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles SaveToolStripMenuItem.Click
Dim FileWriter As StreamWriter
Dim Results as DialiogResult
Results=SaveFileDialog1.ShowDialog
If Results=DialogResult.OK Then
FileWriter=New SreamWriter(SaveFileDialog1.FileName,False)
FileWriter.Write(TxtEditor.Text)
FileWrite.Close( )
End If
End Sub
 Writing code for the print command requires the use of the printDialog control. It
comprises two parts, the first part is to presents a print dialog for the user to set the
options to print and second part is to print the document. click on the print menu item and
enter the code
i- The code to presents a printer dialog
Private Sub PrintToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles PrintToolStripMenuItem.Click
‘Let the user to choose the page range to print
printDialog1.AllowSomePages=True
‘Display the help Button
PrintDialog1.ShowHelp=True
printDialog1.Document=docToPrint
Dim result As DialogResult=PrintDialog1.ShowDialog( )
If(result=DialogResult.OK) Then
docToPrint.Print()
End if

77
End Sub
ii- The code to print the document
Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As
System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
Dim mytext As string
Mytext=Txteditor.Text
Dim PrintFont as New System.Drawing.Font_ (“Arial”, 12, System.Drawing.FontStyle.Regular)
‘Format and print the text
e.graphics.DrawString (mytext, printFont, _System.Drawing.Brushes.Black, 10, 10)
End Sub

Adding Toolbar Icons

First we can look up for some free icons sites in Google to download the icons you intend to
place on your toolbar.
To add item on the tool bar, click on the small icon on the left most corner of the toolbar and
chose buttons from the dropdown list

Right click on the button and choose properties window from the drop down list, then proceed to
change the default image by clicking the three-dot button on the right of the image property.
Choose icon or image file from your hard drive that you wise to load.

78
2-Follow and use internal documentation standards and tools

Building a Database

In the past, people typically deal with data manually like using cards and folders. However, in
present day fast pace global environment and Information age, it is no longer feasible to manage
data manually. Most data are now managed using computer-based database management
systems. Computer-based Database management systems can handle data much faster and more
efficient than human beings do. With the advent of the network and the Internet technologies,
data can now be managed locally and remotely. Companies usually invest heavily in database
management systems in order to run the organizations efficiently and effectively. Database
management systems are used in running payroll system, inventory system, accounting system,
payment system, order handling system, customer relationship management system (CRM) and
more. Some of the commercial database management system (DBMS) is Oracle, Microsoft SQL
server and Microsoft Access

Creating a Database Application in Visual Basic

A database management system typically deals with storing, modifying, and extracting
information from a database. It can also add, edit and delete records from the database. However,
a DBMS can be very difficult to handle by ordinary people or business men who have no
technological backgrounds. Fortunately, we can create user friendly database applications to
handle the aforementioned jobs with the DBMS running in the background. One of the best
programs that can create such database application is none other than Visual Basic.
Visual Basic uses ADO.NET to handle databases. ADO.NET is Microsoft’s latest database
technology which can works with many other advanced database management system such as
Microsoft SQL server.
To begin building the database project in Visual Basic, launch Visual Basic.You can name your
project as Database Project 1 or whatever name you wish to call it. Next, change the default

79
form’s Text property to Contacts as we will be building a database of contact list. There are a
few objects in ADO.NET that are required to build the database.
There are:
 SqlConnection- to connect to a data source in SQL Server
 DataTable -to store data for navigation and manipulation
 DataAdapter- to populate a DataReader
The aforementioned object belongs to the System.Data and the System.Xml namespace.
Therefore, we have to reference them in the beginning before we can work with them. To
reference the ADO.NET object, choose project from the menu then select Database Project 1
properties to display the project properties. Next click the References tab to show the active
references for the project,

Under imported namespaces, make sure system.data, System.Data.Sqlclient are selected,


otherwise check them. Having done that you need to click the Save All button on the toolbar and
then return to the Visual Basic

Creating Connection to Database Using ADO.NET

In Visual Basic, we need to create connection to a database before we can access its data. Before
we begin, let’s create a new database. Since we are using SQL Server 2008 as the database
engine, we will use Microsoft Studio Management Express to create a database with the mdf
extension. We shall name this database file as test.mdf. After creating the database, build a table
called Contacts and create two fields and name them ContactName and State respectively. Enter
a few data in the table and click Save All to save the data. Now we are ready to connect to this
new database.

80
ADO.NET offers a number of connection objects such as OleDbConnection,
SqlConnection and more. OleDbConnection is used to access OLEDB data such as Microsoft
Access whilst SqlCOnnection is used to access data provided by Microsoft SQL server. Since we
will work with SQL database in our example, we will use the SqlConnection object. To initialize
the variable to a new SqlConnection object,
we use the following syntax:Private MyCn As New SqlConnection
Having created the instance of the SqlConnecton object, the next step is to establish a connection
to the data source using the  SQL ConnectionString property.

The syntax is:


MyCn.ConnectionString = “Data Source=lenovo-4903350b\mssmlbiz;
AttachDbFilename=C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\Test.mdf;
”&_
“User Instance=True;Integrated Security=SSPI”
* You need to change the reference to the SQL server (lenovo-4903350b\mssmlbiz) as well as
the path to database file Test.mdf.
After establishing connection to the database, you can open the database using the following
syntax:
MyCn.Open()

Populating Data in ADO.NET

Establishing connection to a database in Visual Basic using SqlConnection alone will not
present anything tangible things to the user to manipulate the data until we add more relevant
objects and write relevant codes to the project.
The next step is to create an instance of the SqlDataAdpater in our code so that we can populate
the Data Table with data from the data source. Besides, you also need to create an instance of the
Data Table. Other than that, you should also create an instance of the SqlCommandBuilder
which is used to manipulate data such as updating and deleting data in the Datatable and send the
changes back to the data source. The statements are:
Private MyDatAdp As New SqlDataAdapter
Private MyCmdBld As New SqlCommandBuilder
Private MyDataTbl As New DataTable
Having created the above of objects, you need to include the following statements in the Sub
Form_Load event to start filling the DataTable with data from the data source. The statements
are as follows:
MyDatAdp = New SqlDataAdapter(“Select* from Contacts”, MyCn)
MyCmdBld = New SqlCommandBuilder(MyDatAdp)
MyDatAdp.Fill(MyDataTbl)
After filling up the DataTable , we need to write code to access the data. To access data in the
DataTable means that we need to access the rows in the table. We can achieve this by using the
DataRow object. For example, we can write the following to access the first row of the table and
present the data via two text boxes with the name txtName and txtState respectively:
Dim MyDataRow As DataRow = MyDataTbl.Rows(0)
Dim strName As String
Dim strState As String
strName = MyDataRow(“ContactName”)
strState = MyDataRow(“State”)

81
txtName.Text = strName.ToString
txtState.Text = strState.ToStringMe.showRecords()

* The two fields being referenced here are ContactName and State. Note Index 0 means first
row.
showRecords() is a sub procedure created to show data in the text boxes. The code is as follows:
Private Sub showRecords()
If MyDataTbl.Rows.Count = 0 Then
txtName.Text = ""
txtState.Text = ""
Exit Sub
End If
txtName.Text = MyDataTbl.Rows(MyRowPosition)("ContactName").ToString
txtState.Text = MyDataTbl.Rows(MyRowPosition)("State").ToString
End Sub

The output interface:

Managing Databases

Browsing Records in Databases 

We will create command buttons and write relevant codes to allow the user to browse the
records forward and backward as well as fast forward to the last record and back to the first
record.
The first button we need to create is for the user to browse the first record. We can use button’s
text << to indicate to the user that it is the button to move to the first record and button’s text >>
to move to the last record.  Besides we can use button’s text < for moving to previous record and
button’s text > for moving to next record.

The code for moving to the first record is:

82
MyRowPosition = 0
Me.showRecords()

The code for moving to previous record is:


If MyRowPosition > 0 Then
MyRowPosition = MyRowPosition – 1
Me.showRecords()
End If

The code for moving to next record is:


If MyRowPosition < (MyDataTbl.Rows.Count – 1) Then
MyRowPosition = MyRowPosition + 1
Me.showRecords()
End If

The code for moving to last record is:


If MyDataTbl.Rows.Count > 0 Then
MyRowPosition = MyDataTbl.Rows.Count – 1
Me.showRecords()
End If

Editing, Saving, Adding and Deleting Records

You can edit any record by navigating to the record and change the data values. However, you
need to save the data after editing them. You need to use the update method of the
SqlDataAdapter to save the data.

The code is:


If MyDataTbl.Rows.Count <> 0 Then
MyDataTbl.Rows(MyRowPosition)(“ContactName”) = txtName.Text
MyDataTbl.Rows(MyRowPosition)(“state”) = txtState.Text
MyDatAdp.Update(MyDataTbl)
End If

You can also add new record or new row to the table using the following code:
Dim MyNewRow As DataRow = MyDataTbl.NewRow()
MyDataTbl.Rows.Add(MyNewRow)
MyRowPosition = MyDataTbl.Rows.Count – 1
Me.showRecords()

The code above will present a new record with blank fields for the user to enter the new data.
After entering the data, he or she can then click the save button to save the data.
Lastly, the user might want to delete the data.

The code to delete the data is:


If MyDataTbl.Rows.Count <> 0 Then
MyDataTbl.Rows(MyRowPosition).Delete()
MyDatAdp.Update(MyDataTbl)
MyRowPosition = 0

83
Me.showRecords()
End If

Self-Check EIS DBA4-


Document Activities
LG05 M05 LO4-SC04

Name: _________________________ Date: _______________

1- What is streamReader?
2- What is streamwriter?
3- _________displays icons that can be used to open a file save a file, viewing a document, printing
a document and more.

4- _____ Visual Basic uses to handle databases


5- ______ is uses to connect to a data source in SQL Server

84
Answer Key EIS DBA4-LG05 M05
LO4-AK 04 Document Activities

1-StreamReader is a tool that enables the streaming of data by moving it from one
location to another so that the user can read it.

2-StreamWriter is a tool that can write data input by the user to a storage device such as
the hard disk.
3-A standard Tool bar
4-ADO.NET
5- SqlConnection

Information EIS DBA4-LG05 M05 LO5 – IS05


Test Code

1-Design and conduct Simple tests to confirm the coding process meets design specification

85
Testing is the tools to save time, reduce costs, and improve quality throughout the entire
development lifecycle.
Testing is an essential part of the development process. Test tools can make the job easier and
more efficient.
Some tests, such as unit tests, are typically created by developers. Yet much of testing is done
by dedicated testers. Testing is a discipline in its own right, and testers play a critical role in most
development teams

In Visual Studio, these tools include the following:


 Ways to gather the results of running tests, including diagnostic data to help determine
the cause of failures.
 A tool for creating and managing test plans.
 Software for creating, configuring, and deploying virtual machines for use in a test
environment.
 Support for manual testing, including things such as the ability to record and
automatically play back a manual test.
 Support for automated testing, including load tests.
Programming errors come in three varieties: syntax errors, run-time errors, and logic errors.
 When you break VB’s rules for punctuation, format, or spelling, you generate a syntax
error. The syntax errors that the editor cannot identify are found and reported by the
compiler as it attempts to convert the code into intermediate machine language.
 A compiler-reported syntax error may be referred to as a compile error.
 The editor can correct some syntax errors by making assumptions and not even report the
error to you.
 If your project halts during execution, it is called a run-time error or an exception.
 Visual Basic displays a dialog box and highlights the statement causing the problem
 When your program contains logic errors, your project runs but produces incorrect results.

2-Document the tests performed

Project Debugging

If you talk to any computer programmer, you will learn that programs don’t have errors, but that
programs get “bugs” in them. Finding and fixing these bugs is called debugging.
For syntax errors and run-time errors, your job is easier. Visual Basic displays the Editor window
with the offending line highlighted. However, you must identify and locate logic errors yourself.
VB has a very popular feature: edit-and-continue. If you are able to identify the run-time error
and fix it, you can continue project execution from that location by clicking on the Continue
button, pressing F5, or choosing Debug / Continue. You also can correct the error and restart from the
beginning.

A Clean Compile

When you start executing your program, the first step is called compiling, which means that the
VB statements are converted to Microsoft Intermediate Language (MSIL). Your goal is to have
no errors during the compile process: a clean compile. Figure shows the Error List window for a
clean compile: 0 Errors; 0 Warnings; 0 Messages.

86
Zero errors, warnings, and messages means that you have a clean compile.

Packaging Applications for distribution

If the error is identify and debug now you need to package them into a distributable from before
you can deploy them to package your application means you need to create an install program so
that the user can install your application in his her computer.

Creating the setup program using publish wizard

To start setting up the program, open the project. Once loaded, click project on the menu and
then choose publish project. Click on publish project and the publish wizard dialog appears.

In publish Wizard dialog, you need to enter a location to publish your application. You have the
options to publish your application to a web site, FTP server or your local drive. We will only
publish the application to local drive. To create the install program in your local drive, you need
to click browse and look for a folder in your hard drive where the files will be setup there. It is
advisable to create a folder before you start publishing your application; here we have created
theVBapps folder in my documents.
Now click the next button and you can see another dialog asking you the options of how you
want your users to install the application. We choose installation from CR_ROM or DVD_ROM.

87
Click next and you will see another dialog asking you where the application will check for
updates. In our case, we choose not to check updates option.

The next dialog will remained you to check your application whether it is ready for deployment.

If you are certain that your application contains no errors then click to finish. The publish Wizard
will start compiling your files and set up the install files. Finally, it will open the folder and
display the install files, including the setup.exe files.

88
3-Make Corrections to the code and the documentation as needed

After correction the error and creating the setup program using publish wizard we have to test the
program.
Now it is time to test out the install program for your project. Click the setup.exe file to start the
installation process. The first dialog that appears issues a security warning as your application
was not licensed digitally. However, since you have created your own application and you are
sure it will not cause any harm to your computer, simply click the install button continue with the
installation process. As soon as the installation complete, it will launch the installed application.

To look up for your newly installed application, you can click the start menu in your window and
click on all programs and you will be see the project folder which contains your project
application where you can click to run the program. To distribute your application, simply copy
the install folder and files to a CD-ROM, a DVD-ROM or a pen drive.

Self-Check EIS DBA4-


Test Code
LG05 M05 LO5-SC05
89
Name: _________________________ Date: _______________

1- What is testing?
2- What are the three error occur in VB?
3- In what time the run time error occurs?
4- When you break VB’s rules for punctuation, format, or spelling, you generate ___ error.
5- Finding and fixing bugs is called ___

Answer Key EIS DBA4-LG05 M05


Test Code
LO5-AK 05

1- Testing is the tools to save time, reduce costs, and improve quality throughout the entire
development lifecycle.
2- Syntax errors, run-time errors, and logic errors.
3- If your project halts during execution, it is called a run-time error or an exception.
4-a syntax error
5- Debugging.

90

You might also like