Professional Documents
Culture Documents
Uc 5
Uc 5
Page 1
Information EIS DBA4-
LG05 M05 LO1 – IS01 Apply basic language syntax and layout
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
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”
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.
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//
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.
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 ;
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)
Operators
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;
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();
}
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)
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
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
}
#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++;
}
}
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;
}
# 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];
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;
}
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
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
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
}
Page 25
Self-Check EIS DBA4-LG05 M05 Apply basic OO principles in the target
LO2-SC02 language
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
Page 27
Page 28
Information EIS DBA4-LG05 M05 LO3 – IS03 Debug code
29
Visual Basic is fully fledged Object-Oriented Programming (OOP) Language.
The Integrated Development Environment of VB2010 Express the IDE Start Page consists of a
few sections, namely:
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.
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.
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
End sub
The output is
34
Private sub……..
Statements/code…..
End sub
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 classifies data into two major data types, the numeric data types and the 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.
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
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.
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.
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
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.
If condition Then
Visual Basic 2010 expression
End if
Example
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.
If condition Then
Visual Basic 2010 expression
Else
Visual Basic 2010 expression
End if
42
Example
Example
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.
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
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.
44
Case expression list 4
.
.
.
Case Else
Block of one or more Visual Basic Statements
End Select
Example
‘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.
‘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
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
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
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
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.
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.
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.
Examples
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
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.
Example
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 Len function:-the length function returns an integer value equals to the length of a
phrase or a sentence, including the empty spaces
Example
52
Out put
Where n is the starting position from the right of the phrase where the portion of the
phrase is going to be extracted
Example
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
Example
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
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 Exp of a number is the exponent value of X , i.e ex ,for example, Exp(1)=e=2.71828182
Example
54
Dim Num1, Num2 As String
Num1=textBox1.text
Num2=Math.Exp(Num1)
Label1.Text=Num2
End sub
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
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 is the function that returns the natural logarithm of a number, For example,
Log (10) =2.302585
Example
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
Example
C=math.sqrt(a^2+b^2)
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 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.
Where n is a number.
Example 15.1
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
Although it is known as user-defined format, we still need to follow certain formatting styles.
Example
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
In Visual Basic, date and time can be formatted using predefined formats and also user-defined
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
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
Example
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
Advanced control in VB are check box, Radio button, List box and combo 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.
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
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.
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
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.
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.
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
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
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.
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.
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)
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
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
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.
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: _______________
71
Answer Key EIS DBA4-LG05 M05
LO3-AK 03 Debug Code
2- The Integrated Development Environment of VB2010 Express the IDE Start Page consists of
a few sections, namely:
3-The most used common controls are Button, Label, Combo Box, List Box, Picture Box and
Textbox.
72
Information EIS DBA4-LG05 M05 LO4 – IS04
Document Activities
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.
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
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.
76
The code of open is the same as reading file code now double click on the Open menu
item and enter the code.
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
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
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,
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.
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
Managing 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.
82
MyRowPosition = 0
Me.showRecords()
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.
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.
83
Me.showRecords()
End If
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.
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
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
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.
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.
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.
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 ___
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