Cpe 3 Object Oriented Programming Laboratory Manual
Cpe 3 Object Oriented Programming Laboratory Manual
MISSION
QUALITY POLICY
Northwest Samar State University commits to
provide quality outcomes-based education,
research, extension and production through
continual improvement of all its programs,
therebyproducing world class professionals.
CORE VALUES
Resilience. Integrity. Service. Excellence.
PEO 1: Graduates will achieve a high level of technical expertise so that they are able to succeed in
positions in computer engineering practice or research, and in other fields they chose to pursue.
PEO 2: Graduates will produce engineering designs that are based on sound principles that consider
functionality, aesthetics, safety, cost effectiveness and sustainability.
PEO 3: Graduates will pursue lifelong learning such as graduate studies and other professional
education.
PEO 4: Graduates will engage in professional service, such as participation in professional society
and community service.
PEO 5: Graduates will fulfill values, professional and ethical responsibilities in the practice of
computer engineering, including social, environmental and economic considerations.
PEO 6: Graduates will be leaders, both in their chosen profession and in other activities.
Course Code: CPE 3
Course Description:
This is an introductory course in computer programming logic. The student will learn algorithms
applicable to all programming languages, including: identifiers, data types, arrays, control structures,
modular programming, generating reports, and computer memory concepts. The student will learn to
use charts commonly used in business and information processing. Program logic will be developed
using flowcharts and pseudo code. Programs will be written using C programming language.
Course Outcomes:
NAME: ___________________________________________________________________
Student
Number:__________________________________________________________________
Course-Year SEM:______________________________________
level:__________________
LABORATORY MANUAL
OOP LAB
Prepared by:
PEO 1: Graduates will achieve a high level of technical expertise so that they are able to
succeed in positions in computer engineering practice or research, and in other fields they chose
to pursue.
PEO 2: Graduates will produce engineering designs that are based on sound principles that
consider functionality, aesthetics, safety, cost effectiveness and sustainability.
PEO 3: Graduates will pursue lifelong learning such as graduate studies and other professional
education.
PEO 4: Graduates will engage in professional service, such as participation in professional
society and community service.
PEO 5: Graduates will fulfill values, professional and ethical responsibilities in the practice of
computer engineering, including social, environmental and economic considerations.
PEO 6: Graduates will be leaders, both in their chosen profession and in other activities.
PROGRAM OUTCOMES
Engineering graduates will be able to:
PO2: Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
PO5: Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modelling to complex
engineering activities with an understanding of the limitations.
PO6: The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent
responsibilities relevant to the professional engineering practice.
PO7: Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of,
and need for sustainable development.
PO8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practice.
PO9: Individual and team work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.
PO10: Communication: Communicate effectively on complex engineering activities with the
Engineering community and with society at large, such as, being able to comprehend and
write effective reports and design documentation, make effective presentations, and
give and receive clear instructions.
PO11: Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a
member and leader in a team, to manage projects and in multidisciplinary
environments.
PO12: Life-long learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological
change.
a. Laboratory observation notes with all the details (Problem statement, Aim,
Algorithm, Procedure, Program, Expected Output, etc.,) filled in for the lab
session.
b. Laboratory Record updated up to the last session experiments.
c. Formal dress code and Identity card.
4. Sign in the laboratory login register, write the TIME-IN, and occupy the computer
system allotted to you by the faculty.
5. Execute your task in the laboratory, and record the results / output in the lab observation
note book, and get certified by the concerned faculty.
6. All the students should be polite and cooperative with the laboratory staff, must maintain
the discipline and decency in the laboratory.
7. Computer labs are established with sophisticated and high end branded systems, which
should be utilized properly.
8. Students / Faculty must keep their mobile phones in SWITCHED OFF mode during the
lab sessions. Misuse of the equipment, misbehaviours with the staff and systems etc.,
will attract severe punishment.
9. Students must take the permission of the faculty in case of any urgency to go out. If
anybody found loitering outside the lab / class without permission during working hours
will be treated seriously and punished appropriately.
10. Students should SHUT DOWN the computer system before he/she leaves the lab after
completing the task (experiment) in all aspects. He/she must ensure the system / seat is
kept properly.
All students must observe the dress code while in the laboratory
Footwear is NOT allowed
Foods, drinks and smoking are NOT allowed
All bags must be left at the indicated place
The lab timetable must be strictly followed
Be PUNCTUAL for your laboratory session
All programs must be completed within the given time
Noise must be kept to a minimum
Workspace must be kept clean and tidy at all time
All students are liable for any damage to system due to their own negligence
Students are strictly PROHIBITED from taking out any items from the laboratory
Report immediately to the lab programmer if any damages to equipment
Lab In – charge
Experiment No. (1) Introduction to
Visual Basic.NET
Object:
To identify main visual basic’s objects and their properties, methods and
events.
Theory:
Visual basic introduced in 1991, visual basic.net introduced in 2002/2003.The latest version of
Microsoft’s Visual Studio, called Visual Studio 2015, includes Visual Basic, Visual C++, Visual C# (C
sharp), Visual F# (F sharp),JScript, and the .NET 4.6 Framework.
Microsoft Visual Basic comes with Visual Studio. You also can purchase VB by itself (without the other
languages but with the .NET Framework). VB is available in an Express version, and in Visual Studio
2010 Professional, Visual Studio 2010 Premium, and Visual Studio 2010 Ultimate.
1
Object Oriented Programming
*Function oriented programming (FOP).
*Functions and subroutines.
*Code executed by run the program.
*Can’t change code through runtime and difficult error correction.
The newer programming languages, such as Visual Basic, C#, and Java,
use a different approach: object-oriented programming (OOP)
Object Model
In Visual Basic you will work with objects, which have properties, methods, and events. Each object is
based on a class.
Objects
Examples of objects are forms and controls. Forms are the windows and dialog boxes you place on the
screen; controls are the components you place inside a form, such as text boxes, buttons, and list boxes.
Properties
Properties tell something about or control the behavior of an object, such as its name, color, size, or
location. Example object. property=value textbox.name= new
Methods
Built in procedure actions associated with objects are called methods. Some typical methods are Close,
Show, and Clear. Each of the predefinedobjects has a set of methods that you can use.
Events
An event occurs when the user takes an action, such as clicking a button,pressing a key, scrolling, or
closing a window.
2
Object Oriented Programming
Classes
Classes contain the definition of all available properties, methods, and events. Each time that you
create a new object, it must be based on aclass. For example, you may decide to place three buttons
on your form. Each button is based on the Button class and is considered one object, called an instance
of the class.
Example1:-
Object-event() command1-click()
End end
The Visual Studio environment is where you create and test your projects.A development environment,
such as Visual Studio, is called an integrated development environment (IDE). The IDE consists of
various tools, including a form designer, which allows you to visually create a form; an editor, for
entering and modifying program code; a compiler, fortranslating the Visual Basic statements into the
intermediate machine code; a debugger, to help locate and correct program errors; an object browser,
to view available classes, objects, properties, methods, and events; and a Help facility.
3
Object Oriented Programming
In versions of Visual Studio prior to .NET, each language had its own IDE.
For example, to create a VB project you would use the VB IDE, and to
create a C++ project you would use the C++ IDE. But in Visual Studio, you
use one IDE to create projects in any of the supported languages.
Solution
Explorer
Window
Holds the
filenames
for the files
New included in
project Your
project and
a list of the
classes
Figure (1.1) Visual Studio IDE with the Start Page open, as it first appears in
Windows 7, without an open project.
STEP 1: Click the Windows Start button and move the mouse pointer to
All
Programs.
STEP 2: Locate Microsoft Visual Studio 2010 or Microsoft Visual Basic
2010.
STEP 3: If a submenu appears, select Microsoft Visual Studio 2010.Visual Studio (VS) will start and
display the Start Page(figure above). If you are using Visual Studio Professional and this is the first time
that VS has been opened on this computer, you may need to select
4
Object Oriented Programming
Visual Basic Development Settings from the Choose Default
Environment.
After you click on New Project this window will pop up:
Click on the first icon Windows Application, and name your first
application and then click ok (As shown in figure 1.3).
Now you can see a small form on the corner of the application, andthe controls
on its left (As shown in figure 1.4).
Let's add a text box: a text box is a text area that allows the user to
enter text.
In the Tool Box on the left, click on TextBox.
Draw a shape on the form to draw the TextBox (Figure 1.5).
After placing the TextBox on the form, you can move anywhere onthe Form.
5
Object Oriented Programming
Now insert a label (Figure1.6).
Find the Label control from the Tool Box and place it on the Form.
Figure (1.3)
Form Designer Window
Tool Box
contain
controls
(objects)
used in
the project
Figure (1.4)
6
Object Oriented Programming
Figure (1.5)
Name the Label1 "Name". To do that right click on Label1, clickon Properties
The Properties window will appear on the right (contain the
properties of the control).
Change the property of Text to Name (figure 1.7):
Add a new Textbox and a new Label and a button as the picture
below, and name the second change the new label's text properties
to Last and the button's text to Get Name (figure 1.8)::
Figure (1.6)
7
Object Oriented Programming
Property
window
of the
label
control
(object)
Figure (1.7)
Figure (1.8)
8
Object Oriented Programming
Writing code:
Double click on the new button that says "Get Name" to go to the
codes page.
You will find a code like this:
End Sub
End Class
Now we will tell the form to produce a message box and show thename and the
last name when we click on "Get Name"
You will enter this code between the second line and the third line:
MsgBox("My Name is " & TextBox1.Text & " " & TextBox2.Text)
Figure (1.9)
9
Object Oriented Programming
Procedure:
Write a V.B Program to make a calculator that calculates two textboxes automatically without any
control to explain how to use textbox to enter numbers. Add three textboxes to the form. Add them in
this order: put thefirst one on the left side, the second on the middle and the third one the right like
figure (1.10):
Figure (1.10)
Discussion:
10
Object Oriented Programming
Experiment No. (2)
Object:
Theory:
Variables
Variables are the memory locations which are used to store values
temporarily. A variable name must begin with an alphabet letter It must
be unique within the same scope. It should not contain any special
character like %, &, !, #, @ or $.The name cannot be a reserved word, such
as Sub or Double.
By default Visual Basic variables are of variant data types. The variant data
type can store numeric, date/time or string data (as shown in table 2.1).
Examples
Dim intAge As Integer
Dim decPayRate As DecimalDim
dblPrice As Double
Private — you can use the Private keyword only for variables declared at
the module, class, or structure, not inside a subroutine. A variable declared
Private is accessible only to code in the same module, class, or structure.
If the variable is in a class or structure, it is available to other
11
Object Oriented Programming
instances of the class or structure. For example, one Customer object can access a Private variable
inside another Customer object.
Static — you can use the Static keyword only for variables declared within
a subroutine or a block within a subroutine. A variable declared Static
keeps its value between lifetimes. For example, if a subroutine sets a Static
variable to 27 before it exits, the variable begins with the value27 the
next time the subroutine executes. The value is stored in memory, so it is
not retained if you exit and restart the whole program. Use a database, the
System Registry, or some other means of permanent storageif you need to
save values between program runs.
Table (2.1)
12
Object Oriented Programming
TYPE of CHARACTERS
Data type characters identify a value’s data type. The following table liststhe data type characters of
Visual Basic.
% Integer& Long
@ Decimal
! Single # Double
$ String
13
Object Oriented Programming
You can specify a variable’s data type by adding a data type character after a variable’s name when you
declare it.
num_desserts = 100
satisfaction_quotient# = 1.23
Using Constants
In addition to reserving (or declaring) variables in a program, you also can declare named constants.
A named constant is a memory location whose value cannot change while the application is running.
Examples
Const dblPI As Double = 3.141593
Const intMAX_HOURS As Integer = 40
Const decTAXRATE As Decimal = .05
Every numeric data type in Visual Basic has a TryParse method that can
be used to convert text to that numeric data type.
dataType.TryParse(text, variable)
Example 1
14
Object Oriented Programming
At times, you may need to convert a number (rather than a string) fromone data type to another.
Convert.method(value)
Example 2
decTaxRate = Convert.ToDecimal(.05)
converts the Double number .05 to Decimal and then assigns the result to the
decTaxRate variable.
Example 3
lblTotal.Text = Convert.ToString(intTotalScore)
converts the integer stored in the intTotalScore variable to String and then
assigns the result to the lblTotal control’s Text property.
The Option Explicit and Option Strict compiler options play an important role in variable declarations.
When Option Explicit is set to On, you mustdeclare all variables before you use them. If Option Explicit
is Off, VisualBasic automatically creates a new variable whenever it sees a variablethat it has not
yet encountered. For example, the following code doesn’t explicitly declare any variables. As it executes
the code, Visual Basic sees the first statement, num_managers = 0. It doesn’t recognize the variable
num_managers , so it creates it. Similarly, it creates the variable iwhen it sees it in the For loop.
15
Object Oriented Programming
Keeping Option Explicit turned off can lead to two very bad problems. First, it silently hides
typographical errors. If you look closely at the preceding code, you’ll see that the statement inside the
For loop increments the misspelled variable num_managrs instead of the correctly spelled variable
num_managers. Because Option Explicit is off, Visual Basic assumes that you want to use a new variable,
so it creates num_managrs . After the loop finishes, the programdisplays the value of num_managers ,
which is zero because it was never incremented
The second problem that occurs when Option Explicit is off is that Visual
Basic doesn’t really know what you will want to do with the variables it
creates for you. It doesn’t know whether you will use a variable as an
Integer, Double, String, or PictureBox.
When Option Strict is turned off, Visual Basic silently converts values from one data type to another,
even if the types are not very compatible. For example, Visual Basic will allow the following code to
try to copy the string s into the integer i . If the value in the string happens to be a number (as in the
first case), this works. If the string is not a number (asin the second case), this throws an error at
runtime.
Dim i As Integer
Dim s As String
s = "10"
i = s ' This works.
s = "Hello"
i = s ' This Fails.
If you turn Option Strict on, Visual Basic warns you of possibly illegal
conversions at compile time.
ARITHMETIC OPERATORS
The following table lists the arithmetic operators provided by Visual Basic. Most programmers should
be very familiar with most of them. The four operators that may need a little extra explanation are \ ,
Mod , < < , and >>, as shown in table (2.2).
Table (2.2)
16
Object Oriented Programming
COMPARISON OPERATORS
Comparison operators compare one value to another and return a Boolean value (True or False),
depending on the result. The following table lists the comparison operators provided by Visual Basic.
The fi rst six ( = , < >
, < , < = , > , and > = ) are relatively straightforward. Note that the Not
operator is not a comparison operator, so it is not listed here. It is described
in the next section, “ Logical Operators. ”, as shown in table (2.3)
Table (2.3)
LOGICAL OPERATORS
Logical operators combine two Boolean values and return True or False, depending on the result. The
following table (2.4) summarizes Visual Basic’s logical operators.
Table (2.4)
17
Object Oriented Programming
Built-in Functions in visual basic 2010
The functions fall into the following basic categories that will be discussed in the following sections at
length(see table 2.5).
*The Now function retrieves the date and time, while Date function retrieves only date
and Time function retrieves only the time.
Table (2.5)
is a very powerful formatting function which can display the numeric values in various forms. The
format of the predefined Format function is: Format (n, "style argument"). Where n is a number and
the list of style arguments is given in Table (2.6).
18
Object Oriented Programming
Table (2.6)
19
Object Oriented Programming
Figure (2.1)
The syntax is
The Exp of a number x is the exponential value of x, i.e. exp . For example,
Exp(1)=e=2.71828182
The syntax is
Math.Exp (number)
The Fix function truncates the decimal part of a positive number andreturns the largest integer
smaller than the number. However, when the
20
Object Oriented Programming
number is negative, it will return smallest integer larger than the number.
For example, Fix(9.2)=9 but Fix(-9.4)=-9.
The Int is a function that converts a number into an integer by truncating its decimal part and the
resulting integer is the largest integer that is smaller than he number. For example
The Log function is the function that returns the natural logarithm of a number. For example,
Log(10)=2.302585.
The Rnd is very useful when we deal with the concept of chance and probability. The Rnd function
returns a random value between 0 and 1. Random numbers in their original form are not very useful
inprogramming until we convert them to integers.
The Round function is the function that rounds up a number to a certain number of
decimal places. The Format is Round (n, m) which means to round a number n to m
decimal places. For example, Math.Round (7.2567, 2) =7.26
End Sub
String functions
21
Object Oriented Programming
The Mid function is used to retrieve a part of text form a given phrase.
The format of the Mid Function is
Mid(phrase, position,n)
x=Mid(“newdesign”,3,2) , x=wd
The Left function extracts the left portion of a phrase. The format is
Microsoft.Visualbasic.Right ("Phrase", n)
- Len function
The Trim function trims the empty spaces on both side of the phrase. The
format is
Ltrim (" Visual Basic")= Visual basic, Rtrim ("Visual Basic ") =
Visual Basic
22
Object Oriented Programming
Where n is the position where the Instr function will begin to look forthe
embedded phrase. For Example:
Asc("B")=66, Asc("&")=38
Procedure
Write a V.B program behave like a virtual dice. (make use of Rnd
and Int functions).
Discussion
Write a V.B program to explain how to use Now, Date, Time functions.
23
Object Oriented Programming
Experiment No. (3) IF…..Then +
Loop Structures
Object
Allow the user to learn arrays and Visual Basic control structures such as
If ..... Then.... Else, Select ....Case, in addition to the loop structures such
as Do while ....Loop, For Next, etc.
Theory
Visual Basic supports control structures such as if... Then, if. Then
...Else, Select...Case, and Loop structures such as Do While. Loop,
For. Next etc method.
The If. . Then selection structure performs an indicated action only when the condition
is True; otherwise the action is skipped.
If <condition> Then
statement
End If
The If...Then ....................................... Else selection structure allows the programmer to specify
that a different action is to be performed when the condition is True than
when the condition is False.
24
Object Oriented Programming
Syntax of the If...Then...Else selection
E.x.:
If average>50 Then
txtGrade.Text = "Pass"
Else
txtGrade.Text = "Fail"
End If
Nested If...Then...Else selection structures test for multiple cases by placing If...Then...Else selection
structures inside If...Then...Else structures.
Method 1
Method 2
25
Object Oriented Programming
statements
Else
If < condition 3 > Then
statements
Else
Statements
End If
End If
EndIf
EX: Assume you have to find the grade using nested if and display in atext box
Nested If Statements
End If
Select Case is preferred when there exist multiple conditions becauseusing If...Then..ElseIf
statements will become too messy.
26
Object Oriented Programming
Select Case test expression
End Select
Example1: 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= "Excellence"
Case Is >= 70
Label2.Text= "Good"
Case Is >= 60
Label3.Text = "Above Average"
Case Is >= 50
Label4.Text= "Average"
Case Else
Label5.Text = "Need to work harder"
End Select
End Sub
'Examination Marks
Dim mark As Single
27
Object Oriented Programming
mark = Textbox1.Text
Select Case mark
Case 0 to 49
Label1.Text = "Need to work harder"
Case 50 to 59
Label1.Text = "Average" s
Case 60 to 69
Label1.Text= "Above Average"
Case 70 to 84
Label1.Text = "Good"
Case 85 to 100
Label1.Text= "Excellence"
Case Else
Label1.Text= "Wrong entry, please reenter the mark"
End Select
End Sub
Example2: Grades in high school are usually presented with a single capital letter such as A, B, C,
D or E. The grades can be computed asfollow:
'Examination Marks
28
Object Oriented Programming
The output of example2 shown the following figure:
Figure (3.1)
Choose function
29
Object Oriented Programming
LOOPIN
Looping is required when we need to process something repetitively until a certain condition is met.
For example, we can design a program that adds a series of numbers until the sum exceeds a certain
value, or a program that asks the user to enter data repeatedly until he/she keys in the word 'Finish'. In
Visual Basic 2010, we have three types of Loops, they are the For.....Next loop, the Do loop. and the
While. End while loop.
Sometimes the user might want to get out from the loop before the whole repetitive process is executed;
the command to use is Exit For. To exit a For.....Next Loop, you can place the Exit For statement within
the loop; and it is normally used together with the If....Then.... statement. For its application, you can
refer to example
Dim n as Integer
For n=1 to 10
If n>6 then
Exit For
End If
30
Object Oriented Programming
Else
n+=n
Next
End If
Next
DO….LOOP
The formats of Do Loop are:
a) Do While condition
Loop
b) Do
c) Do Until condition
Loop
d) Do
31
Object Oriented Programming
Example5: Do Loop example explanation
TextBox1.Text=counter
counter +=1
Loop
Do
TextBox1.Text=counter
counter+=1
Figure (3.2)
32
Object Oriented Programming
Dim y, z, r As Integer
y = 1 : z = Val(TextBox1.Text)
If z = 0 Then
y= y
Else
For r = z To 1 Step -1
y=y*r
Next r
End If
Label1.Text = y
Figure (3.3)
Y=x^2-3*x x>0 OR Y=2*x+x^3 x=0 OR Y=sqr(100+3*x) x<0
Dim x As Integer
Dim y As Single
x = Val(TextBox1.Text)
If x > 0 Then
y=x^2-3*x
ElseIf x = 0 Then
y=2*x+x^3
Else
y = Math.Sqrt(100+3*x)
End If
TextBox2.Text = y
33
Object Oriented Programming
ARRAYS
Syntax—Version 1
Dim arrayName(highestSubscript) As dataType
Syntax—Version 2
Dim arrayName() As dataType = {initialValues}
Syntax
Array.Sort(arrayName)
Array.Reverse(arrayName)
Example 11
Dim intNums() As Integer = {1, 3, 10, 2, 4, 23}
Array.Sort(intNums)
sorts the values in the intNums array in ascending order as follows: 1, 2, 3, 4,
10, 23
Example 12
Dim intNums() As Integer = {1, 3, 10, 2, 4, 23}
Array.Reverse(intNums)
reverses the order of the values in the intNums array as follows: 23, 4, 2, 10, 3,
1
Example 13
Dim intNums() As Integer = {1, 3, 10, 2, 4, 23}
Array.Sort(intNums)
Array.Reverse(intNums)
Sorts the values in the intNums array in descending order as follows: 23,10, 4, 3, 2, 1.
34
Object Oriented Programming
Example14: will store four names in a one-dimensional String array named
strFriends. It then will display the contents of the array in three label
controls named lblOriginal, lblAscending, and lblDescending. In the
lblOriginal control, the names will appear in the same order as in the array.
In the lblAscending and lblDescending controls, the names will appear in
ascending and descending order, respectively.
35
Object Oriented Programming
Figure (3.4)
DYNAMIC ARRAY
Redim statementSyntax
ReDim [Preserve] arrayName(highestSubscript)
Example 15
Example 16
Dim intNums() As Integer = {100, 120, 230}
ReDim intNums(4)
36
Object Oriented Programming
Result of ReDim statement:
100 0
120 0
230 0
0
0
Example 17
Dim intNums() As Integer = {100, 120, 230}
ReDim intNums(1)
100 100
120 120
230
An EMPTY array is an array that contains no elements. You declare anempty array using an empty
set of braces, like this:
Syntax—Version 1
{Dim | Private} arrayName(highestRowSubscript, highestColumnSubscript)
As datatype
Syntax—Version 2
{Dim|Private}arrayName(,) As dataType =
{{initialValues},…{initialValues}}
Declares and initializes (to 0) a procedure-level array named intScores;the array has six rows and
four columns
37
Object Oriented Programming
Example 19—Version 2’s syntax
Declares and initializes a class-level array named strProducts; the arrayhas three rows and three
columns.
Procedure
Discussion
38
Object Oriented Programming
Experiment No. (4) Form –
TextBox – Menus
Object
Allow the user to understand the properties, events and methods of form
and menus.
Theory
Forms
The terms form and window describe the same entity. A window is what
the user sees on the Desktop when the application is running. A form is the
same entity at design time. The proper term is Windows form. Forms have
a built-in functionality that is always available without any programming
effort on your part.
Minimize
Caption Title bar Maximize
or restore
Control close
menu icon
Control menu
39
Object Oriented Programming
Figure (4.1)
AcceptButton, CancelButton
These two properties let you specify the default Accept and Cancel buttons. The Accept button is the
one that’s automatically activated when you press Enter (the OK caption), the Cancel button is the one
that’s automatically activated when you hit the Esc key.
AutoScroll
The AutoScroll property is a True/False value, will be automatically attached to the form if the form is
resized to a point that not all its controls are visible.
AutoScrollPosition
This property is available from within your code only, and it indicates the number of pixels that the
form was scrolled up or down. Its initial value is zero, and it takes on a value when the user scrolls the
form (provided that the AutoScroll property is True). Use this property to find out the visible controls
from within your code or to scroll the form from within your application’s code to bring a specific
control into view.
FormBorderStyle
The FormBorderStyle property determines the style of the form’s border.
MinimizeBox, MaximizeBox
These two properties, which specify whether the Minimize and Maximizebuttons will appear
MinimumSize, MaximumSize
These two properties read or set the minimum and maximum size of aform
KeyPreview
This property enables the form to capture all keystrokes before they’re passed to the control that has
the focus. Some forms perform certain actions when you hit a specific key (the F5 key for refreshing
the form being a very common example, To handle a specific keystroke at the
40
Object Oriented Programming
form’s level, set the form’s KeyPreview property to True and insert the
appropriate code in the form’s KeyDown or KeyUp event handler, The
same keystrokes are then passed to the control with the focus, unless you
kill the keystroke by setting its SuppressKeystroke property to True when
you process it on the form’s level.
Example1:
If Char.IsLetterOrDigit(e.KeyChar) Then
Select Case UCase(e.KeyChar)
Case "1", "2", "3", "4", "5", "6", "7", "8", "9", "0"
TextBox1.SelectedText = e.KeyChar
Case "A", "B", "C", "D", "E", "F"
TextBox1.SelectedText = UCase(e.KeyChar)
End Select
e.Handled = True
End If
Handling Keystrokes
Although the Tab key is the Windows method of moving to the next control
on the form, most users will find it more convenient to use the Enter key
for that purpose. The Enter key is the most important one onthe keyboard.
When the user presses Enter in a single-line TextBox, for example, the
obvious action is to move the focus to the following control. I included a
few statements in the KeyDown event handlers of the TextBox controls to
move the focus to the following one:
41
Object Oriented Programming
’ process the Enter key
End If
Once you can figure out the active control’s type, you need a method of simulating the
Tab keystroke from within your code so you don’t have to code every TextBox control’s
KeyDown event. An interesting method of the Form object is the ProcessTabKey
method, which imitates the Tab keystroke. Calling the ProcessTabKey method is
equivalent to pressing the Tab key from within your code. The method accepts a
True/False value as an argument, which indicates whether itwill move the focus to
the next control in the tab order (if True) or to the previous control in the tab order. Start
by setting the form’s KeyPreview property to True and then insert the following
statements in the form’s KeyDown event handler:
StartPosition, Location
The StartPosition property, which determines the initial position of the form when it’s first displayed
TopMost
This property is a True/False setting that lets you specify whether theform will remain on top of
all other forms in your application
Form Events
42
Object Oriented Programming
The Resize, ResizeBegin, and ResizeEnd Events: the Resize event is fired
every time the user resizes the form by using the mouse.
A dialog box is simply a modal form. When you display forms as dialog boxes, change the border of the
forms to the setting FixedDialog and invoke them with the ShowDialog method. Modeless forms are
more difficult to program because the user may switch among them at any time. Moreover, the two
forms that are open at once must interact with one another. When the user acts on one of the forms, it
might necessitate changes in the other, and you’ll see shortly how this is done. If the two active forms
don’t need to interact, display one of them as a dialog box.
When you’re finished with the second form, you can either close it by
calling its Close method or hide it by calling its Hide method. The Close
method closes the form, and its resources are returned to the system. The
Hide method sets the form’s Visible property to False; you can still access
a hidden form’s controls from within your code, but the user can’t interact
with it.
43
Object Oriented Programming
A typical application has more than a single form. When an application
starts, the main form is loaded. You can control which form is initially
loaded by setting the startup object in the project Properties window. To
open this dialog box, right-click the project’s name in the Solution Explorer
and select Properties. In the project’s Properties pages, switch to the
Application tab and select the appropriate item in the Startup Form combo
box. By default, the IDE suggests the name of the first form it created,
which is Form1.
The controls on a form can be accessed by the code in another form because the default value of the
Modifiers property of the controls on a form is Friend, which means that all components in a solution
can access them. Other settings of the Modifiers property are Public (any applicationcan access the
control) and Private (the control is private to the form to which it belongs and cannot be accessed from
code outside its own form).
Basic Properties
MultiLine
This property determines whether the TextBox control will hold a singleline or multiple lines of text.
MaxLength
44
Object Oriented Programming
This property determines the number of characters that the TextBoxcontrol will accept.
ScrollBars
This property lets you specify the scroll bars
CharacterCasing
This property tells the control to change the casing of the characters
PasswordChar
Hides text with single char.
ReadOnly, Locked
If you want to display text on a TextBox control but prevent users from editing it (such as for an
agreement or a contract they must read, software installation instructions, and so on), you can set the
ReadOnly property toTrue.
Text
The most important property, which holds the control’s text.
Text-Selection Properties
The TextBox control provides three properties for manipulating the text selected by the
user:
SelectedText
This property returns the selected text
SelectionStart, SelectionLength
The SelectionStart property returns or sets the position of the first character of the
selected text
The SelectionLength property returns or sets the length of the selected text.
Dim x As String
TextBox1.SelectionStart = 2
TextBox1.SelectionLength = 3
45
Object Oriented Programming
x = TextBox1.SelectedText
MsgBox(x)
Events
Methods
*setfocus (place the cursor in a specified text box , give it the focus).
e.g. txt.setfocus (this will move cursor to the box named txt).
Example2 to explain how to dealing with password programs by using the textbox
properties
Also explain how to make use of forms events when using more than one form in
your project First form1 to enter valid password, then second form2 is (MODAL Form)
to enter two numbers to add them and show the result in the third form3 by using
CLICK event of the form3 and if user forget to click on the form and decide to close
form3, then we shall make use of event CLOSE of form3 to remember user to before
(he/she) leaving.
Figure 4.2
46
Object Oriented Programming
Dim pasword As String
If TextBox1.Text = "" Then
MsgBox("please enter the password")
Else
TextBox1.SelectionStart = 0
TextBox1.SelectionLength = 7
pasword = TextBox1.SelectedText
TextBox1.Tag = "example"
If pasword = TextBox1.Tag Then
MsgBox("true password")
Form2.ShowDialog()
Else
MsgBox("invalid password")
End If
End If
And another code for the change event of the textbox control.
TextBox1.PasswordChar = "*"
Figure 4.3
Figure (4.4)
The code for CLICK event of form3, and CLOSE event of form3:
47
Object Oriented Programming
Private Sub Form3_Click
Me.TextBox1.Text = Val(Form2.TextBox1.Text) +
Val(Form2.TextBox2.Text)
End Sub
Figure (4.5)
Can change or set any property of menustrip or any of menuitems by the properties window. NOTE:
The most convenient method of editing a menu is to use the Items Collection Editor window (you can
set all the properties of each menu item in the dialog box without having to switchto the Properties
window). Right click on menustrip then choose Edit Items…. , finally the Items Collection Editor window
will opened.
Right click on menustrip then choose Insert Standard Items will add the menus(File,
Edit, Tools, Help) in your form.
48
Object Oriented Programming
Enabled Some menu commands aren’t always available. The Paste
command, for example, has no meaning if the Clipboard is empty (or if it
contains data that can’t be pasted in the current application).
When a menu item is selected by the user, it triggers a Click event. TheExit command’s code would
be something like the following:
Sub menuExit(…) Handles menuExit.Click
End
End Sub
If you need to execute any cleanup code before the application ends, place it in
the
CleanUp() subroutine and call this subroutine from within the Exit item’s
Click event handler:
Sub menuExit(…) Handles menuExit.Click
CleanUp()
End
End Sub
NOTE: The same subroutine must also be called from within the FormClosing event handler of the
application’s main form because some users might terminate the application by clicking the form’s Close
button.
DropDownOpened event
(In effect, when the user clicks a menu item that leads to a submenu). Edit menu of just about any
application contains the ubiquitous Cut/Copy/Paste commands. These commands are not meaningful
at all times. If the Clipboard doesn’t contain text, the Paste command should be disabled. If no text is
selected, the Copy and Cut commands should also be disabled. Here’s how you could change the status
of the Paste command from within the DropDownOpened event handler of the Edit menu:
If My.Computer.Clipboard.ContainsText Then
PasteToolStripMenuItem.Enabled = True
Else
PasteToolStripMenuItem.Enabled = false
End If
Likewise, to change the status of the Cut and Copy commands, use the
following statements
in the DropDownOpened event of the ToolStripMenuItem that represents the
Edit menu:
49
Object Oriented Programming
If txtEditor.SelectedText.Trim.Length > 0 Then
CopyToolStripMenuItem.Enabled = True
CutToolStripMenuItem.Enabled = True
Else
CopyToolStripMenuItem.Enabled = False
CutToolStripMenuItem.Enabled = False
End If
Access Keys
Access keys allow the user to open a menu by pressing the Alt key and a letter key (for example: Alt+E
to open Edit menu). To assign an access key to a menu item, insert the ampersand symbol (&)in front
of the character you want to use as an access key in the ToolStripMenuItem’s Text property.
Procedure
Repeat the above (example2) but with different FORM3 EVENTS. And
add more mathematics operations.
Discussion
50
Object Oriented Programming
2- Write V.B.NET program to implement Password login that give user three trials to
enter right password, otherwise the program ended.
Hint: use Tag and Passwordchar properties of TextBox control. And static
variable to count the user trials.
Figure (4.6)
51
Object Oriented Programming
Experiment No. (5)
Object
To explain how the user can communicate with an application during the
run time by using MessageBox – InputBox – DialogueBox.
Theory
MessageBox
At times, an application may need to communicate with the user during
runtime; one means of doing this is through a message box. MessageBox
is one of those dialog boxes that you will use often as a developer.
Table (5.1)
Table (5.2)
52
Object Oriented Programming
Which button is default mean which one be active with pressing enterkey.
Table (5.3)
Argument Meaning
text text to display in the message box; use sentence capitalization
caption text to display in the message box’s title bar; use book title
capitalization
buttons: buttons to display in the message box; can be one of thefollowing
constants:
MessageBoxButtons.AbortRetryIgnore
53
Object Oriented Programming
MessageBoxButtons.OK (default setting)
MessageBoxButtons.OKCancel
MessageBoxButtons.RetryCancel
MessageBoxButtons.YesNo
MessageBoxButtons.YesNoCancel
icon icon to display in the message box; typically, one of the following
constants:
MessageBoxIcon.Exclamation
MessageBoxIcon.Information
MessageBoxIcon.Question
MessageBoxIcon.Stop
defaultButton button automatically selected when the user presses Enter;can be one of the following
constants:
Example 1
MessageBox.Show("Record deleted.", "Payroll",
MessageBoxButtons.OK, MessageBoxIcon.Information)
Displays an information message box that contains the message “Recorddeleted.”
Figure (5.1)
Example 2
MessageBox.Show("Delete this record?", "Payroll",
54
Object Oriented Programming
MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation,
MessageBoxDefaultButton.Button2)
Displays a warning message box that contains the message “Delete this record?”
Example 3
Dim dlgButton As DialogResult
dlgButton =MessageBox.Show("Delete this record?", "Payroll",
MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation,
MessageBoxDefaultButton.Button2)
If dlgButton = DialogResult.Yes Then
instructions to delete the record
End If
Example4: this is a simple example(using MsgBox method) to explain thereturn value(integer) of the
VbOkCancel message box which will return number 1 if the user click ok button, if user click cancel the
returned value is 2.
55
Object Oriented Programming
Figure (5.2)
Dim r As Integer
r = MsgBox("this is new example", vbOKCancel + vbInformation +
vbDefaultButton1 + _
vbApplicationModal, "message title")
MsgBox(r)
56
Object Oriented Programming
THE OPENFILEDIALOG CONTROL
Many Windows applications process data from files, so you need an interface to select files to open and
save. The .NET Framework provides the OpenFileDialog and SaveFileDialog classes to do just that. You
can use OpenFileDialog as a .NET class by declaring a variable of that type in your code and modifying
its properties in code without dragging a controlonto the Forms Designer., or as a control by dragging
the control from theToolbox onto the form at design time.
Example: Public Class Dialogs
Common OpenFileDialog Control Properties
Table (5.4)
PROPERTY DESCRIPTION
AddExtension Indicates whether an extension is automatically added to a
filename if
the user omits the extension. This is mainly used in the
FileName Indicates the path and filename of the selected file in the
dialog box.
FileNames Indicates the path and filenames of all selected files in the
dialog box.
Thisis a read-only property.
Filter Indicates the current filename filter string, which determines
the options
that appear in the Files of Type: combo box in the dialog
57
Object Oriented Programming
FilterIndex Indicates the index of the filter currently selected in the
dialog box.
InitialDirectory Indicates the initial directory displayed in the dialog box.
Multiselect Indicates whether the dialog box allows multiple files to be
selected.
ReadOnlyChecked Indicates whether the read-only check box is selected.
SafeFileName Indicates the filename of the selected file in the dialog box.
OpenFileDialog Methods
➤ OpenFile opens the file selected by the user with read-only
permission. The file is specified by the FileName property.
➤ Reset resets all properties of the Open dialog box to their
default values.
➤ ShowDialog shows the dialog box.
strFileName = OpenFileDialog1.FileName
TextBox1.Text = strFileName
End If
Table (5.5)
58
Object Oriented Programming
PROPERTY DESCRIPTION
AddExtension Indicates whether an extension is automatically added to a
filename if the
user omits the extension
AutoUpgradeEnabled Indicates whether this dialog box should automatically upgrade
its
Appearance behavior when running on different versions of
Windows.
When false, it will appear with XP styles.
CheckFileExists Indicates whether the dialog box displays a warning if the user
specifies a
filename that does not exist. This is useful when you want the
user to save a
file to an existing name.
CheckPathExists Indicates whether the dialog box displays a warning if the user
specifies a
path that does not exist.
CreatePrompt Indicates whether the dialog box prompts the user for permission
to create
a file if the user specifies a file that does not exist.
DefaultExt Indicates the default file extension
DereferenceLinks Indicates whether the dialog box returns the location of the file
referenced
by the shortcut or whether it returns the location of the shortcut
itself.
FileName Indicates the filename of the selected file in the dialog box. This
is a
readonly property.
FileNames Indicates the filenames of all selected files in the dialog box.
This is a
readonly property that is returned as a string array.
Filter Indicates the current filename filter string, which determines the
options
that appear in the Files of Type: combo box in the dialog box.
FilterIndex Indicates the index of the filter currently selected in the dialog
box
InitialDirectory Indicates the initial directory displayed in the dialog box
OverwritePrompt Indicates whether the dialog box displays a warning if the user
specifies a
filename that already exists.
ShowHelp Indicates whether the Help button is displayed in the dialog box
SupportMultiDotted
Extensions Indicates whether the dialog box supports displaying and saving
files that
have multiple filename extensions
Title Indicates the title that is displayed in the title bar of the dialog
box
59
Object Oriented Programming
ValidateNames Indicates whether the dialog box should accept only valid
Win32 filenames
SaveFileDialog Methods
Table (5.6)
PROPERTY DESCRIPTION
AllowScriptChange Indicates whether the user can change the character set specified
in the Script drop-down box to display a character set
other than the one currently displayed
Color Indicates the selected font color
Font Indicates the selected font
FontMustExist Indicates whether the dialog box specifies an error condition
60
Object Oriented Programming
if theuser attempts to enter a font or style that does not exist
MaxSize Indicates the maximum size (in points) a user can select
MinSize Indicates the minimum size (in points) a user can select
ShowApply Indicates whether the dialog box contains an Apply button
ShowColor Indicates whether the dialog box displays the color choice
ShowEffects Indicates whether the dialog box contains controls that
allow the user to specify strikethrough, underline,
and text color options
ShowHelp Indicates whether the dialog box displays a Help button
E.X.:
FontDialog1.ShowDialog()
FontDialog1.ShowColor = True
FontDialog1.ShowDialog()
Table (5.7)
PROPERTY DESCRIPTION
AllowFullOpen Indicates whether users can use the dialog box to define custom
colors
AnyColor Indicates whether the dialog box displays all available colors in
the set of
basic colors
Color Indicates the color selected by the user
CustomColors Indicates the set of custom colors shown in the dialog box
61
Object Oriented Programming
FullOpen Indicates whether the controls used to create custom colors are
visible when the dialog box is opened
‘Show the Color dialog and if the user clicks the OK button,
‘update the background color of the form
If ColorDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
Me.BackColor = ColorDialog1.Color
End If
Table 5.8
PROPERTY DESCRIPTION
AllowCurrentPage Indicates whether the Current Page option button is
enabled
AllowPrintToFi Indicates whether the Print to File check box is enabled
AllowSelection Indicates whether the Selection option button is
enabled
AllowSomePages Indicates whether the Pages option button is enabled
Document Indicates the print document used to obtain the printer
settings
PrinterSettings Indicates the printer settings that the dialog box will be
modifying
PrintToFile Indicates whether the Print to File check box is
checked
ShowHelp Indicates whether the Help button is displayed
ShowNetwork Indicates whether the Network button is displayed
62
Object Oriented Programming
Table 5.9
PROPERTY DESCRIPTION
Description Provides a descriptive message in the dialog box.
RootFold Indicates the root folder from which the dialog box
should start browsing.
SelectedPath Indicates the folder selected by the user.
ShowNewFolderButton Indicates whether the Make New Folder button is
shown in the dialog box
Example 9:
Private Sub btnBrowse_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnBrowse.Click
‘Set the FolderBrowser dialog properties
With FolderBrowserDialog1
.Description = "Select a backup folder"
.RootFolder = Environment.SpecialFolder.MyComputer
.ShowNewFolderButton = False
End With
‘Show the FolderBrowser dialog and if the user clicks the
‘OK button, display the selected folder
If FolderBrowserDialog1.ShowDialog = Windows.Forms.DialogResult.OK
Then
txtFile.Text = FolderBrowserDialog1.SelectedPath
End If
End Sub
The input dialog box contains a message, an OK button, a Cancel button, and an input area where the
user can enter information. The message in the dialog box should prompt the user to enter the
appropriate information in the input area. The user closes the dialog box by clicking the OK button,
Cancel button, or Close button. The value returned by the InputBox function depends on the button the
user chooses. If the user clicks the OK button, the InputBox function returns the value containedin
the input area of the dialog box; the return value is always treated as a string. If the user clicks either
the Cancel button in the dialog box or the Close button on the dialog box’s title bar, the InputBox
function returns an empty string. The empty string is represented by the String.Empty constant in
Visual Basic.
InputBox Function
Syntax
63
Object Oriented Programming
InputBox(prompt[, title][, defaultResponse])
Example10
strName = InputBox("First name:", "Name Entry")
Displays an input dialog box that shows First name: as the prompt, Name Entry in the title bar, and an
empty input area. When the user closes the dialog box, the assignment statementassigns the user’s
response to aString variable named strName.
Example11
strState = InputBox("State name:", "State", "Alaska")
Displays an input dialog box that shows State name: as the prompt, State in the title bar, and Alaska in
the input area. When the user closes the dialog box, the assignment statement
assigns the user’s response to a String variable named strState.
Example12
Const strPROMPT As String =
"Enter a sales amount. Click Cancel to end."
Displays the input dialog box shown in Figures below.When the user closes the dialog box, the
assignment statement assigns the user’s response to a String variable namedstrInputSales.
Example13
Displays an input dialog box that shows How old are you? as the prompt,
Discount Verification in the title bar, and an empty input area. When the
user closes the dialog box, the TryParse method converts the user’s
response from String to Integer and then stores the result in anInteger
variable named intAge.
Procedure
64
Object Oriented Programming
Write AV.B program to keep track of the number of sales amountsentered
by the sales manager, uses the accumulator variable to total the sales
amounts entered by the user
Discussion
65
Object Oriented Programming
Experiment No. (6)
Object
Allow the user to select one or more items from a list of items.
Theory
Checkbox :It allows the user to select one or more items by checking thecheckbox/checkboxes concerned.
Example1: In this example, the user can enter text into a textbox and format
the font using the three checkboxes that represent bold, italic and underline.
Figure (6.1)
66
Object Oriented Programming
The code is as follow:
67
Object Oriented Programming
End If
End Sub
* The above program uses the CheckedChanged event to respond to the user selection
by checking a particular checkbox, it is similar to the click event.
Radio Button
it operates differently from the check boxes. While the checkboxes work independently and allows 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 2: Here is an example which allows the user to select one color
only.
Figure (6.2)
68
Object Oriented Programming
End Sub
Although the user may only select one item at a time, he may make more than one selection if those
items belong to different categories. For example, the user wish to choose T-shirt size and color, he
needs to select one color and one size, which means one selection in each category. This is easily
achieved in VB2010 by using the Groupbox control under the containers categories. After inserting the
Groupbox into the form, you canproceed to insert the radio buttons into the Groupbox. Only the radio
buttons inside the Groupbox are mutually exclusive, they are not mutually exclusive with the radio
buttons outside the Groupbox.
NOTE: The GroupBox tool is located in the Containers section of the toolbox, because a
group box serves as a container for other controls. You can use a group box to visually separate
related controls from other controls on the form.
The ListBox, CheckedListBox, and ComboBox controls present lists of choices from which the user can
select one or more of the items. The ListBox displays a list of choices from which the user can select
zero choices, one choice, or multiple choices. Th e number of choices the user can select is controlled
by the list box’s SelectionMode property. The default value for the property is One, which allows the
user to select only one choice at a time.
69
Object Oriented Programming
Note: the user can enter new item in the ComboBox, but in listbox user can’t enter new item.
Basic Properties
In the following sections, you’ll find the properties that determine the functionality of the List-Box,
CheckedListBox, and ComboBox controls.These properties are usually set at design time,but you can
change the settings from within your application’s code.
IntegralHeight
This property can be set to a True/False value that indicates whether thecontrol’s height will be
adjusted to avoid the partial display of the last item.
Items
The Items property is a collection that holds the list items for the control.
SelectionMode
This property, which applies to the ListBox and CheckedListBox controls only, determines how the user
can select the list’s items., The possible values of this property
Table 6.1
Value Description
deselects an item in the list. You must click all the items you want
to select.
MultiExtended Extended multiple selection: Press Shift and click the mouse (or
press one of
70
Object Oriented Programming
all the items between the previously selected item and the current
selection.
Press Ctrl and click the mouse to select or deselect multiple single Items in the list.
Text
Sorted property
True, the item is sorted along with the existing items and then placed inits proper position in the
list.
To manipulate a ListBox control from within your application, youshould be able to do the
following:
Example3: The following loop adds the elements of the array words to a
ListBox control, one at a time:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim words() As String = {"new", "old", "big", "small"}
Dim i As Integer
For i = 0 To words.Length - 1
ListBox1.Items.Add(words(i))
Next
End Sub
71
Object Oriented Programming
Figure (6.3)
Then, to iterate through all the items on the control, use a loop such as the
following:
Dim i As Integer
For i = 0 To ListBox1.Items.Count - 1
{ statements to process item ListBox1.Items(i) }
Next
ListBox1.Items.Insert(index, item)
ListBox1.Items.Clear
72
Object Oriented Programming
argument. The syntax of the CopyTo method is as follows, where
destination is the name of the array that will accept the items, and index is
the index of an element in the array where the first item will be stored:
ListBox1.CopyTo(destination, index)
ListBox1.Items.RemoveAt(index)
The index parameter is the order of the item to be removed, and the firstitem’s order is 0.
End If
Selecting Items
The ListBox control allows the user to select either one or multiple items,depending on the setting of
the SelectionMode property.
NOTE: the ComboBox does not allow the selection of multiple items, it provides
only the SelectedIndex and SelectedItem properties.
To iterate through all the selected items in a multiselection ListBoxcontrol, use a loop such as
the following:
73
Object Oriented Programming
NOTE: The itm variable should be declared as Object because the items in the ListBox control are
objects.
Example4:The ListBox Demo application (shown in Figure below) demonstrates the basic
operations of the ListBox control.
Figure (6.4)
74
Object Oriented Programming
Dim ListItem As String
ListItem = InputBox("Enter new item’s name")
If ListItem.Trim <> "" Then
sourceList.Items.Add(ListItem)
End If
NOTE: Clear button is very simple using Clear method to clear the corresponding list
sourceList.SelectedIndices(0)))
sourceList.Items.Remove(sourceList.Items(
sourceList.SelectedIndices(0)))
End While
End Sub
The second single-arrow button transfers items in the opposite direction.
75
Object Oriented Programming
NOTE: The destination control (the one on the right) doesn’t allow the selection of multiple items, so
you can use the SelectedIndex and SelectedItem properties. The event handler that moves a single item
from the right to the left ListBox is shown next:
sourceList.Items.Add(destinationList.SelectedItem)
destinationList.Items.RemoveAt(destinationList.SelectedIndex)
Two of the most useful methods of the ListBox control are the FindString and FindString- Exact
methods, which allow you to quickly locate any item in the list.
locates a string that partially matches the one you’re searching for; FindStringExact finds an exact
match.
The syntax for both methods is the same, where searchStr is the string
you’re searching for:
itemIndex = ListBox1.FindString(searchStr)
An alternative form of both methods allows you to specify the index where the search begins:
NOTE:Both methods return the index of the item you’re searching for on the control, or the
value –1 if no such item exists.
76
Object Oriented Programming
There are three types of ComboBox controls. The value of the control’s
DropDownStyle property determines which box is used, these values are
shown in the table below.
Table (6.2)
Value Effect
DropDownList This style is a drop-down list from which the user can
select one of its
items but can’t enter a new one. The control displays a
single item,and
the list is expanded as needed.
Simple The control includes a text box and a list that doesn’t drop
down. The
user can select from the list or type in the text box
NOTE: Properties,methods, and events are similar to listbox except that deletion of
multiselect property, and addition of style property
Shows the code used to fill the combo boxes with values. As you do with a list box, you
use the Items collection’s Add method to add an item to a combo box. You can use any
of the following properties to select a default item, which will appear in the text portion
of the combo box:
SelectedIndex, SelectedItem, or Text. If no item is selected, the SelectedItem and Text properties
contain the empty string, and the SelectedIndex property contains –1 (negative one).
NOTE: to load Combobox or Listbox with items we shall use the load event of form.
77
Object Oriented Programming
Figure (6.5)
NOTE: If the combo box is a DropDownList style, where the text portion is not
editable, you can use the SelectedItem and Text properties interchangeably.
78
Object Oriented Programming
Example 6: to give Squareroot ,Exponential, or power of numbers by putting the numbers combobox1
and chose the operation user want toimplement from and display result in text1box.
Figure (6.6)
Put the following code in the command button(calculate):
If ComboBox2.SelectedIndex = 0 Then
TextBox1.Text = Math.Sqrt(Val(ComboBox1.Text))
ElseIf ComboBox2.SelectedIndex = 1 Then
TextBox1.Text = Math.Exp(Val(ComboBox1.Text))
Else
TextBox1.Text = Val(ComboBox1.Text) * Val(ComboBox1.Text)
End If
The ScrollBar and TrackBar controls let the user specify a magnitude by moving a selector between its
minimum and maximum values. The TrackBar control is similar to the ScrollBar control, but it doesn’t
cover a continuous range of values. The TrackBar control has a fixed number of tick marks and users
can place the slider’s indicator to the desired value. In short, the ScrollBar control should be used
when the exact value isn’tas important as the value’s effect on another object or data element. The
TrackBar control should be used when the user can type a numeric value and the value your application
expects is a number in a specific range— for example, integers between 0 and 100 or a value between
0 and 5 inches in steps of 0.1 inches (0.0, 0.1, 0.2 . . . 5.0). The TrackBar control is preferred to the
TextBox control in similar situations because there’s
79
Object Oriented Programming
no need for data validation on your part. The user can specify only valid
numeric values with the mouse.
Maximum The control’s maximum value. The default value is 100, but you can set it to any value that
you can represent with the Integer data type.
Figure (6.7)
80
Object Oriented Programming
Figure (6.8)
NOTE: Set the max property to 120, and min to -60, then write this code.
tempc As Integer
Then write the following code in the Scroll event of the VscrollBar1
control
Private Sub VScrollBar1_Scroll()
Figure (6.9)
81
Object Oriented Programming
The TrackBar Control
The TrackBar control is similar to the ScrollBar control, but it lacks the granularity of ScrollBar.
Suppose that you want the user of an application to supply a value in a
specific range, such as the speed of a moving object. Moreover, you don’t
want to allow extreme precision; you need only a few distinct settings. The
user can set the control’s value by sliding the indicator or by clicking on
either side of an indicator. Figure below The Inches application
demonstrates the use of the TrackBar control in specifying an exact value
in specific range
Figure (6.10)
82
Object Oriented Programming
Procedure
Using the FindString and FindString-Exact methods to find the string in textbox that match the list item,
if entered string by user match the list item, then display message “found”, if partially match then
display “partially found”, else display “not found”
Figure (6.12)
Discussion
1- Users can select one color and one size of the T-shirt example (example2)
mentioned above.
Figure (6.11)
83
Object Oriented Programming
Experiment No. (7)
Object
Using procedure and function which are useful for condensing repeated
operations.
Theory
Visual Basic programs can be broken into smaller logical components(small piece of the code) called
Procedures There are two types of Sub procedures in Visual Basic: event procedures andindependent
Sub procedures. An event procedure is a Sub procedure that is associated with a specific object and
event, such as a button’s Click event or An independent Sub procedure, is a procedure that is
independent of any object and event(your own Sub procedure). An independent Sub procedure is
processed only when called (invoked) from code. Procedures are useful for condensing repeated
operations such asthe frequently used calculations, text and control manipulation etc.
It is easier to debug a program with procedures, which breaks a program into discrete logical limits
make it easy to understand). Procedures usedin one program can act as building blocks for other
programs with slight modifications(independent Sub procedures are used extensively in large and
complex programs, which typically are written by a team of programmers). Together, subroutines and
functions are sometimes called routines or procedures. They arealso sometimes called methods.
syntax
84
Object Oriented Programming
A sub procedure can be placed in standard, class and form modules. Each time the procedure is called,
the statements between Sub and End Sub are executed. The syntax for a sub procedure is as follows:
Under Scope, Public is selected to create a procedure that can be invoked outside the module, or Private
to create a procedure that can be invoked only from within the module.
Call procedureName([argumentList ])
Steps
1. Click a blank line in the Code Editor window. The blank line can beanywhere
between the Public Class and End Class clauses. However, it must be
outside any other Sub or Function procedure.
2. Type the Sub procedure header and then press Enter. The Code Editorautomatically
enters the End Sub clause for you.
Note: the procedure can input and return vlaues through its arguments,and not has an output
data type,also procedure may not has input or output arguments like:
Example1
Sub testproc(x as integer,y as string)
Sub testnew()
Example2:
Sub newsub(valu as integer)
Msgbox “the number is=” & valu
End sub
So the input to this procedure is the vlue of the integer variable value
85
Object Oriented Programming
Example3::
Sub calc(x,y,s1,s2,s3 as integer,s4 as single)S1=x+y
S2=x-y
S3=x*y
S4=x/y
End sub
It's clear from this example that the procedure’s arguments(x and y) considered as input values to the
procedure And in the same procedure consider the arguments(s1,s2,s3,s4) as outputs arguments.
Function Procedures
Functions are like sub procedures, except they return a value to thecalling procedure. useful for taking
one or more pieces of data, called arguments and performing some tasks with them. Then the functions
returns a value that indicates the results of the tasks complete within the function.
Syntax
Private Function procedureName([parameterList]) As dataType
statements
Return expression
End Function
The statement’s syntax is Return expression, where expression represents the one and only value that
will be returned to the statement invoking the function. The data type of the expression must agree
with the data typespecified in the As dataType section of the function’sheader.
Steps
1. Click a blank line in the Code Editor window. The blank line can be anywhere
between the Public Class and End Class clauses.However, it must be outside any
other Sub or Function procedure.
2. Type the Function procedure header and then press Enter. The
Code Editor automatically enters the End Function clause for you.
86
Object Oriented Programming
Example 4
Private Function GetNewPrice(ByVal dblOld As Double) As Double
' increases current price by 5% and returns new price
Dim dblNew As Double
dblNew = dblOld * 1.05
Return dblNew
End Function
Example 5
Private Function GetNewPrice(ByVal dblOld As Double) As Double
' increases current price by 5% and returns new price
Return dblOld * 1.05
End Function
NOTE: You can invoke a function from one or more places in an application’s
code.
NOTE: A Function procedure returns a value and a Sub Procedure does not return a value.
NOTE: In the function declaration,must declare the output datatype of the function which is
differ from sub procedure that function return just one output(result) By it’s Return statement.
NOTE: Method — A generic name for a named set of commands. In Visual Basic, both subs
and functions are types of methods.
Example6::
Function test(valu as integer) as string
Return "the age is" & valu
End function
*To invoke the function from the body of program put this code in button-
click as follows
Dim st as string
St=test(20)
MsgBox(st)
Important Note::there are two ways to passing the arguments value to and from the procedure
to the main program
Every variable has both a value and a unique address that represents its location in the computer’s
internal memory. Visual Basic allows you to pass either a copy of the variable’s value or the variable’s
address to the receiving procedure. Passing a copy of the variable’s value is referred to as passing by
value. Passing a variable’s address is referred to as passing by reference. The method you choose—by
value or by reference— depends on whether you want the receiving procedure to have access to the
variable in memory. In other words, it depends on whether you want
87
Object Oriented Programming
to allow the receiving procedure to change the variable’s contents. To
illustrate, assume you have a savings account at a local bank. During a
conversation with your friend Melissa, you mention the amount of money
you have in the account. Sharing this information with Melissa is similar
to passing a variable by value. Knowing your account balance does not give
Melissa access to your bank account. It merely provides informationthatshe
can use to compare to the balance in her savings account. The savings
account example also provides an illustration of passing information by
reference. To deposit money to or withdraw money from your account, you
must provide the bank teller with your account number. The account
number represents the location of your account at the bank and allows the
teller to change the account balance. Giving the teller your bank account
number is similar to passing a variable by reference. The account number
allows the teller to change the contents of your bank account, similar to the
way the variable’s address allows the receiving procedure to change the
contents of the variable.
First: passing by reference or some times called by address of the argument.in this way the argument
vlue will be changed by the calling program and the called procedure
Second: passing by value,in this way the argument will retain it’s value inthe calling program(main
program),but will changed in the called program.
Example8:: sub test(byval x,byref y), it means that x will be passing by its
value, and y passing by its address
NOTE::if we want to exit procedure or function for any reason or condition, we can write in
the body of the procedure Exit sub,,,,or exit function
Example9 to explain passing by reference and by value, this example just give an explination to the
concept of passing variables by using two variables i, j as example as in the following form:
88
Object Oriented Programming
Al-Mustansiriyah University Third Class
Faculty of Engineering
Computer Engineering Department Software Engineering lab
Dim x, y As Integer
x=3
y=2
MsgBox("in main program x y equal to " & x & " " & y)
Call sample(x, y)
MsgBox("after first call x y equal to " & x & " " & y)
Call sample(x, y)
MsgBox("after second call x y equal to " & x & " " & y)
End Sub
Run the program, then you will get the following results
Figure (7.1)
89
Al-Mustansiriyah University Third Class
Faculty of Engineering
Computer Engineering Department Software Engineering lab
Example 10 of using addsub procedure to sum three dgrees of student,and avg function to give the
average Here the code explain how to input degrees through the procedure then call it in the body of
the avg function And invoke the function and procedure by command1 code
Figure (7.2)
90
Figure (7.3)
NOTE::avg() function not take any inputs but return output} In the following example for the
same program see how can input being through avgfunction like this Avg(d1 as integer,d2 as
integer,d3 as integer) and finally give the same result as the previous program
Errors often occur due to incorrect input from the user. Error handlingcan help make the program
error-free, An error-free program can run efficiently, Therefore a good programmer should be more
alert to the parts of program that could trigger errors and should write errors handlingcode to help the
user in managing the errors.
There are three error types:
In VB can write sub routine to handle the run-time error by writing routine to correct the Expected
errors in our program if occur.
NOTE: VB2010 has improved a lot in built-in errors handling compared to Visual Basic 6. For
example, when the user attempts to divide a number by zero, Vb2010 will not return an error
message but gives the 'infinity' as the answer.
Visual Basic 2010 still supports the VB6 errors handling syntax, that is the On Error GoTo
program_label structure. Although it has a more advanced error handling method, we shall deal with
that later. We shall now learn how to write errors handling code in VB2010. The syntax for errors
handling (in VB6) is
where program_label is the section of code that is designed by the programmer to handle the error
committed by the user. Once an error is detected, the program will jump to the program_label section
for error handling.
Lbl_ErrorMsg.Visible = False
firstNum = Txt_FirstNumber.Text
secondNum = Txt_SecondNumber.Text
Exit Sub 'To prevent error handling even the inputs are valid
error_handler:
Lbl_Answer.Text = "Error"
Lbl_ErrorMsg.Visible = True
End Sub
End Class
VB2010 has adopted a new approach in handling errors, or rather 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
End Try
Example12:
The code
Lbl_ErrorMsg.Visible = False
Try
firstNum = Txt_FirstNumber.Text
secondNum = Txt_SecondNumber.Text
Lbl_Answer.Text = answer
Catch ex As Exception
Lbl_Answer.Text = "Error"
Lbl_ErrorMsg.Visible = True
End Try
End Sub
End Class
The output
Figure (7.5)
Table (7.1)
Section Description
Try The Try section is where you place code that might cause an
exception. You can place all of a procedure’s code within the Try
section, or just a few lines.
Catch Code within the Catch section executes only when an exception
occurs; it’s the code you write to catch the exception.
Finally Code within the Finally section occurs when the code within the
Try and/or Catch sections completes. This section is where you
place your cleanup code—code that you always want executed,
regardless of whether an exception occurs.
NOTE: If no exception occurs, code within the Catch section is ignored.
NOTE: When all statements within the Finally section finish executing, execution
jumps to the statement immediately following End Try.
NOTE: Like other code structures, Visual Basic has a statement that can be used to exit a
Try...End Try structure at any time: Exit Try. Note, however, that if you use Exit Try, code
jumps to the Finally section and then continues with the statement immediately following the
End Try statement.
You’ll probably also want to tell the user what type of exception occurred. To do this, you must have a
way of knowing what exception was thrown. This is also important if you intend to write code to deal
withspecific exceptions. The Catch statement enables you to specify a variable to hold a reference to
an Exception object. Using an Exception object, you can get information about the exception. The
following is thesyntax used to place the exception in an Exception object:
NOTE: the exception object has many properties, here we just mention the message property.
The Message property of the Exception object contains the text that describes the specific
exception that occurred.
At times, you’ll anticipate a specific exception being thrown. For example, you might write code that
attempts to open a file when the file does not exist. In such an instance, you’ll probably want the
program to perform certain actions when this exception is thrown. When you anticipate a specific
exception, you can create a Catch section designed specifically to deal with that one exception. Recall
from the previous section that you can retrieve information about the current exception by using a
Catch statement, such as
Catch objException As Exception
Notice that this structure has two Catch statements. The first Catch statement is designed to
catch only an overflow exception; it doesn’t catch exceptions of any other type. The second
Catch statement doesn’t care what type of exception is thrown; it catches all of them. The
second Catch statement acts as a catchall for any exceptions that aren’t overflow exceptions
because Catch sections are evaluated from top to bottom, much as Case statements are in the
Select...Case structure. You could add more Catch sections to catch other specific exceptions if
the situation calls for it.
Example13:
Try
Some statements
Catch e As OverflowException
Catch e As OutOfMemoryException
Catch e As IndexOutOfRangeException
End try
Procedure
1- Write VB program to build sub routine (call it geometry), to calculate the area
and primeter of circle:::geometry(radius as single,primeter as single,area as
single)…..hint primetercircle=2*pi*radius…….area=pi*(radius)^2
2- Write VB program to implement function that arrange the student degrees
ascendant, and then print in labels the largest and smallest degree ,finally print
the average of the student.
Discussion
1- Write VB program to divide two numbers,if user enter wrong data then calling
the error handling routin using (ON ERROR GOTO method) with resume
statement and then execute the same program with resume next.
2- Repeat previous example with message property, Run the project and click
the button.
3- Write sample of VB program that implement more than one exception type to
handle the errors may be occurred according to these exceptions, such as the
exception types mentioned in the last example.
Experiment No. (8)
Object
Code in Visual Basic is stored in the form of modules. The three kind ofmodules are Form Modules,
Standard Modules and Class Modules.
Instance — When a class is created, the resulting object is an instance ofthe class’s definition.
Sdtandard or code Module A code block that isn’t a class but which can contain Sub
and Function methods Used when only a single copy of code or data is needed in
memory
VB2010 allows users to write programs that break down into modulesand are knows as classes or
types. An object can be created out of a class and it is known as an instance of the class, example is
student class is a subclass of the human class while your son John is an instance of the student class.
VB2010 is a full Object Oriented Programming Language have three core technologies namely
encapsulation, inheritance and polymorphism.
Encapsulation refers to the creation of self-contained modules that bind processing
functions to the data. These user-defined data types are called classes. Each class
contains data as well as a set of methods which manipulate the data. The data
components of a class are called instance variables and one instance of a class is an
object. For example, in a library system, a class could be member, and John and Sharon
could be two instances (two objects) of the library class.
Inheritances
Classes are created according to hierarchies, and inheritance allows the structure and
methods in one class to be passed down the hierarchy. That means less programming is
required when adding functions to complex systems. If a step is added at the bottom of
a hierarchy, then only the processing and data associated with that unique step needs to
be added. Everything else about that step is inherited.
NOTE: The ability to reuse existing objects is considered a major advantage of object
technology.
Polymorphism
Object-oriented programming allows procedures about objects to be created whose
exact type is not known until runtime. For example, a screen cursor may change its
shape from an arrow to a line depending on the program mode. The routine to move the
cursor on screen in response to mouse movement would be written for "cursor," and
polymorphism allows that cursor to take on whatever shape is required at runtime. It
also allows new shapes to be easily integrated.
Creating a Class
You define a class using the Class statement, which you enter in a class file.
Class statement
Syntax
1. Click Project on the menu bar and then click Add Class. The Add New Item dialog box
opens with Class selected in the middle column of the dialog box.
2. Type the name of the class followed by a period and the letters vb in the
Name box, and then click the Add button.
NOTE: can create class by right click on the project name in the solution explorer and then
choose ADD then choose class.
After you define a class, it then can be used to instantiate one or more
objects.
Syntax – Version 1
{Dim | Private} variableName As className
variableName = New className
Syntax – Version 2
{Dim | Private} variableName As New className
CreatingPropertyProcedures
Set ocontact=nothing
Example 3:Now make test on the class contact Place a command button on
Form1. In the Click event for the command1 button (caption=class test), type the
following:
Figure 8.1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e AsSystem.EventArgs) Handles
Button1.Click
Dim ocontact As contact
ocontact = New contact
With ocontact
.firstnam = "aaa"
.lastnam = "bbb"
.birthdat = #5/2/1990#
End With
MsgBox(ocontact.firstnam & " " & ocontact.lastnam & " " &ocontact.birthdat)
ocontact = Nothing
End Sub
Figure 8.2
Creating Methods
Now we can create any method we need and call it as method of the class
MsgBox "my name is " & firstnam & " " & lastnam & " " & "i was born on" &
birthdat
End Sub
This method name is speak. And we can call it from the code window of the form
module.
End Sub
Figure 8.3
One of true benefits of working with class modules is that instantiate multiple copies
of same class,assign each instance its own properties.the following example
demonstrates the use of two different copies of contact objects in same procedure of
form module.
ocontact1.speak()
ocontact2.speak()
ocontact1 = Nothing
ocontact2 = Nothing
End Sub
After running the program, the result will be:
Figure 8.4
Figure 8.5
PUBLIC Variables
When a variable in a class is declared using the Public keyword, it can be accessed by
any application that contains an instance of the class.
To enter the Public variables in the class definition:
1. Enter the following three Public statements:
Figure 8.6
Private variables are not visible to applications that contain an instance of the class A
class’s Private variables can be used only by instructions within the class itself
Example5:
Private _dblLength As Double
Private _dblWidth As Double
For an application to assign data to or retrieve data from a Private variable in a class,
it must use a Public property. In other words, an application cannot directly refer to a
Private variable in a class. Rather, it must refer to the variable indirectly, through the
use of a Public property.
NOTE:initializes the Private variables directly uses the Public properties to initialize
the Private variables indirectly
A Public Property procedure creates a property that is visible to any application that
contains an instance of the class.
Property procedureSyntax
Public [ReadOnly | WriteOnly] Property propertyName[(parameterList)] As
dataType
Get
[instructions]
Return privateVariable
End Get
Set(ByVal value As dataType)
[instructions]
privateVariable = {value | defaultValue}
End Set
End Property
Example 6 – an application can both retrieve and set the Side property’s value
Private _intSide As Integer
Public Property Side As Integer
Get
Return _intSide
End Get
Set(ByVal value As Integer)
If value > 0 Then
_intSide = value
Else
_intSide = 0
End If
End Set
End Property
Example 7– an application can retrieve, but not set, the Bonus property’s value
Private _dblBonus As Double
Public ReadOnly Property Bonus As Double
Get
Return _dblBonus
End Get
End Property
Example 8 – an application can set, but not retrieve, the AnnualSales property’s
value
Private _decAnnualSales As Decimal
Public WriteOnly Property AnnualSales As Decimal
Set(ByVal value As Decimal)
_decAnnualSales = value
End Set
End Property
Constructor
Syntax
Public Sub New([parameterList])
instructions to initialize the class’s Private variables
End Sub
Example 9 (default constructor)
Public Sub New() initializes the Private
_dblLength = 0 variables directly
_dblWidth = 0
End Sub
Example 10 (parameterized constructor) Public Sub
New(ByVal dblL As Double,ByVal dblW As Double)
Length = dblL
Width = dblW uses the Public properties
End Sub to initialize the Private
Method(sub or function) that is not a constructorSyntax
variables indirectly
Public {Sub | Function} methodName([parameterList]) [As dataType]
instructions
End {Sub | Function}
Example 11 (coded as a Function procedure)
Public Function GetArea() As Double
Return _dblLength * _dblWidth
End Function
Example 12 (coded as a Sub procedure)
Public Sub GetArea(ByRef dblA As Double)
dblA = _dblLength * _dblWidth
End Sub
A code module contains only code – declarations, procedures and function – that are
used by other files in the project. They are not associated with a class or form and
contain no objects or event procedures. Like forms, they are saved in the project as a
file with a .vb extension.
When you create a large application with multiple forms, many times you will find that
you will need to access data or functions/procedures from several differentforms.
Using a code module to store this information that all files have potential access to
avoids duplication of code and makes it easier to maintain the application if you need
to modify or update shared information.
Module Names and Module Files - The content of a module begins with the Module
statement and ends with an End Module statement. The syntax is:
Module ModuleName
[contents of module]
End Module
Adding a Module
Once you have added a code module, you add code for sub procedures and functions
to it, just like you would do for a form.
Module-Level Variables
A variable declared inside a module but not inside a procedure or function is called a
module-level variable. The same rules about the scoped of class-level variables in a
form apply to module-level variables in a module.
1. A module-level variable in a standard module is accessible to any procedure
or function in the standard module.
2. If a module-level variable is declared with the Dim or Private keywords, the
variable is NOT accessible to statements outside the module. This type of
variable is said to have module scope.
3. If a module-level variable is declared with the Public keyword, it is accessible
to all other forms and statements outside the module. This type of variable is
said to have global scope. Many programmers prefix global variables with the
letter g_ to document that it is a global variable.
Example 13: create module call it module1, then built in it subroutine that display
message when we call it form window as following:
Module1 Sub
display()
MsgBox (“first program in module”)
End module
Then we can call it from form code window by writing this statement
Module1.display()
FILE PROCESSING IN VB.NET
In addition to getting data from the keyboard and sending data to the computer screen,
an application also can get data from and send data to a file on a disk. Getting data from
a file is referred to as “reading from the file,” and sending data to a file is referred to as
“writing to the file.” Files to which data is written are called output files, because the
files store the output produced by an application. Files that are read by the computer are
called input files, because an application uses the data in these files as input. Most input
and output files are composed of lines of text that are both read and written sequentially.
In other words, they are read and written in consecutive order, one line at a time,
beginning with the first line in the file and ending with the last line in the file. Such
files are referred to as sequential access files, because of the mannerin which the lines
of text are accessed. They also are called text files, because they are composed of lines
of text. Examples of text stored in sequential access files include an employee list, a
memo, and a sales report.
Three basic file types are native to Windows (and MS-DOS before it) and can be
processed by application programs. These are:
Table 8.1
binary files Binary files are files which contain data elements that
are stored in native machine format. Examples would be
executable files (such as .EXE or .DLL files) and files
produced by applications such as Excel and Word
(.XLS and .DOC files). This would also include data
files (record-oriented files) that store one or more fields
(such as an Integer field) in native machine format.
random files Random files are data files that support "direct access"
by record number. This means that the application can
go directly to the desired record in a file rather than
reading through all the preceding records to get to the
desired record (as would be required with a text file).
VB.NET provides functionality to process text and binary files through the
System.IO namespace and also supports re-tooled versions of earlier file
processing functions through the Microsoft.VisualBasic namespace. Random
files can also be processed, but only via the MS.VB namespace.
To process text files using the System.IO namespace, you use the FileStream object
to refer to the file being processed, and the StreamReader object if processing the file
for input or the StreamWriter object if processing the file for output. You then use the
methods of the appropriate object to process the file. Methods of the StreamReader
object include Peek, Read, ReadLine, ReadToEnd, and Close. Methods of the
StreamWriter object include Write, WriteLine, and Close.
To process text files using the Microsoft.VisualBasic namespace, the FileOpen and
FileClose functions are used to open and close the file, respectively. If processing the
file for input, the Input, LineInput, InputString, and EOF are among the functions
you might use. If processing the file for output, Write, WriteLine, Print, and
PrintLine are among the functions you might use.
To process random files, you must use the Microsoft.VisualBasic namespace, and the
same functions that are used process binary files are used to process random files:
FileOpen, FileClose, FileGet, and FilePut. However, the arguments to these functions
in this case will be appropriate to random file processing.
The FileStream class is used to create an object that will reference the file that will be
processed by the program. The syntax for declaring a FileStream object, as it will be
used in the examples that follow, is:
Where
Table 8.2
path is a string that refers to the full path and filename of the file to be processed.
As in the example above, you can use a reference like
My.Application.Info.DirectoryPath & "\somefile.txt" or any other path/file
reference, such as "C:\SomeDirectory\SomeFile.dat".
mode is an enumeration that specifies how the file should be open or created. The
possible values are:
FileAccess.Read Data can be read from the file, but not written to it.
FileAccess.ReadWrite Data can be read from and written to the file.
FileAccess.Write Data can be written to the file, but not read from it.
share is an enumeration that specifies restrictions on how other processes can access the
file. The possible values are:
FileShare.None Other processes may neither read from nor write to the fil
FileShare. ReadWrite Any process can read from or write to the file.
FileShare.Write Other processes may write to the file.
FileShare.Read Other processes may read from the file.
IO.File.method(fileName)
Table 8.3
Method Description
CreateText opens a sequential access file for output
AppendText opens a sequential access file for append
Example 15
outFile = IO.File.CreateText("F:\Chap22\pay.txt")
opens the pay.txt file for output; creates a StreamWriter object and assigns it to the
outFile variable
Example 16
outFile = IO.File.AppendText("report.txt")
opens the report.txt file for append; creates a StreamWriter object and assigns it to the
outFile variable
After opening a file for either output or append, you can begin writing data to it. You
write data to a sequential access file using either the Write method or the WriteLine
method.
Writing data to a sequential access file
Syntax
streamWriterVariableName.Write(data)
streamWriterVariableName.WriteLine(data)
Example 17
outFile.Write("Hello")
Result the next character will appear
Hello| immediately after the letter o
Example 18
outFile.WriteLine("Hello")
Result
Hello the next character will
| Appear on the next line
streamWriterVariableName.Close().
Where
Example 21
If IO.File.Exists("report.txt") = True Then
determines whether the report.txt file exists in the current project’s bin\Debug folder;
you also can write the If clause as If IO.File.Exists("report.txt") Then
ReadLine methodSyntax
streamReaderVariableName.ReadLine
Example 22
strMessage = inFile.ReadLine
reads a line of text from the sequential access file associated with the inFile variable
and assigns the line, excluding the newline character, to the strMessage variable.
Peek method
Syntax
streamReaderVariableName.Peek
Example 23
Do Until inFile.Peek = –1
strLineOfText = inFile.ReadLine
MessageBox.Show(strLineOfText)
Loop
reads each line of text from the sequential access file associated with the inFile
variable, line by line; each line (excluding the newline character) is assigned to the
strLineOfText variable and is then displayed in a message box
Peek Looks ahead to the next available character in the input stream
without actually advancing to that next position. If no character is
available, Peek returns -1. (This method is convenient to test for
end-of-file.)
Read Reads the next character from the input stream.
ReadLine Reads the next line of characters from the input stream into a
string.
ReadToEnd Reads the data from the current position in the input stream to the
end of the stream into a string. (This method is often used to read
the entire contents of a file.)
Close Closes the StreamReader and its associated FileStream object.
Example24: this is program to explain how to write and read from sequential file a
text box for entering a name or any text. The Write to File button will write the name
to a sequential access file. The Read from File button will read each name from the
sequential access file and display each in the readtext box. (The textbox1 control’s
Multiline and ReadOnly properties are set to True, and its ScrollBars property is set to
Vertical.)
TextBox2
TextBox1
Figure 8.7
End Sub
Write the following code in the read from the file button:
End Sub
Table (8.5)
Function Description
FreeFile Returns an Integer value representing the next file number
available for use by the FileOpen function.
FileOpen Opens a file for input or output. (Analagous to the Open
statement in classic VB.)
Input Reads a comma-delimited field from a text file and assigns it to a
variable. (Analagous to the Input statement in classic VB.)
LineInput Reads a single line from an open sequential file and assigns it to a
String variable. (Analagous to the Line Input statement in classic
VB; also analagous to the ReadLine method of the
StreamReader object.)
InputString Reads a specified number of characters from a text or binary file
into a String variable. (Analagous to the Input function in classic
VB; similar to the ReadToEnd method of the StreamReader
object.)
EOF Returns a Boolean value indicating whether or not the end of a
file opened for input or random access has been reached.
Write and Writes data to a text file. Automatically writes the data in comma-
WriteLine delimited format, enclosing string fields in quotes when
necessary. (Analagous to the Write statement in classic VB.)
Print and Writes data to a text file. (similar to the WriteLine method of the
PrintLine StreamWriter object, but with additional functionality.)
FileClose Closes an open file.
FileOpen
Syntax:
FileName: Required. String expression that specifies a valid file name — may
include directory or folder, and drive.
Mode: Required. Enum specifying the file mode. Possible values are:
Table 8.6
Access Optional. Enum specifying the operations permitted on the open file. These
parameters is restrict the user ability to change the file by prevent him from
writing, just reading or make him able to read and write and so on.
Share: Optional. Enum specifying the operations restricted on the open file by other
processes. These parameters used in network environment to decide whether other
processes can fully reach(read or write) the file, or we can lockwrite(prevent user from
write on file mean make it readonly), or lockread(user can only able to write and so on.
Example 25:
FileOpen(1,"C:\ProgramFiles\EmpMaint\EMPLOYEE.TXT", penMode.Input)
FreeFile
function to supply you with a file number that is not already in use by the system. To
use it, declare an integer variable, then assign FreeFile to it, as follows:
intEmpFileNbr = FreeFile
In the Open statement (and any other statement that refers to this file), use the integer
variable For example:
FileClose
Close the opened file and free all system resources used by this file
Syntax: fileclose(filenumber)
Example 26: to open text file name it employee1, to write employee name and
employee number, then read the content into TextBox. Make properties multiline for
the text3 =true, readonly, and vscroll.
Figure 8.8
intEmpFileNbr = FreeFile()
FileOpen(intEmpFileNbr, “D:\employee1.txt”, OpenMode.Append)
WriteLine(intEmpFileNbr, TextBox1.Text, Val(TextBox2.Text))
FileClose(intEmpFileNbr)
FileClose(inred)
Procedure
B- Repeat the geometry subroutine by using subroutine built inmodule then call
subroutine in the form window.
C- Write VB.NET program to write and read from file usin readtoend method
with other methods you learned from this lecture.
Discussion
Theory
What Is a Database?
A database is a container for storing relational, structured information. A
relational database is one that stores information in tables composed of
columns and rows. What makes a database unique is that it is designed to
preserve relationships and make data easily retrievable.
A record is a group of related fi elds that contain all of the necessary data
about a specifi c person, place, or thing.
DBMS
Databases are maintained by special programs, such as Microsoft Office
Access and SQL Server, oracle…etc. These programs are called database
management systems (DBMSs). data organized in tables with relationships
between tables.
SQL
To access or update the data stored in the database, you use a special language, the Structured Query
Language (SQL).all major DBMSs support it. SQL is a nonprocedural language, which means that SQL
doesn’t provide traditional programming structures such as If statements or loops. Instead, it’s a
language for specifying the operation you want to perform against a database at a high level.
NOTE: By the way, the SQL version of SQL Server is called T-SQL, which stands for Transact- SQL.T-
SQL is a superset of SQL and provides advanced programming features that are not available with SQL.
NOTE: you can use Access as well as non-Microsoft databases such as Oracle as DBMS
engines.
NORMALIZATION
The reason for breaking the information we want to store in a database into separate
tables is to avoid duplication of information The process of breaking the data into
related tables that eliminate all possible forms of information duplication is called
normalization.
Example1: if you have table of authors and their books you really have the same
author with more books names, so you need to break the information to two tables one
for authors and the other for books then make relationship between the two tables.
*A relational database can contain one or more tables for example we can build
database call it dbauthor which contain two tables one call it authors and the other is
books, then we can make relationship between the two tables by some unique field has
the same name and same data type in the two tables but in the authors table this field
must has primary key and in the books table the field has foreign key, also authors
table call it the parent( or master) table, but the books table call it the child(or the
details) table.
Example2: in this example will learn how to built database give it name dbauthor
and two tables(authors and books) by using Microsoft office access as DBMS.
1- open Microsoft office access, then choose blankdatabse option, then name the
database (dbauthor) the file name space, then click the create button.
2- point the table1 by the mouse then choose design view in the tool bar, finally name
the table authors.
3- create three fields (id,authorname,title), and make the datatype of the id field is
autonumbering which will be the primary key field.
Primary key
Figure 9.1
4- now built the second table, open create menu, choose table in the tool bar of the
create menu, now point the table2 by the mouse then click design view from the tool
bar.
5- create five fields(id, booktitle, pages, price, bookdate), before closing the table put
the mouse on the id field and right click on the primary key icon to remove this key
because we shall make this field as foreign key, make datatype of this id field is
autonumber like id field in the author table.
Foreign key
Figure 9.2
6- open database tools menu, then choose relationships from tool bar of the menu,
click on authors and books tables and click add.
Figure 9.3
7- now establishing the relationship by continuous click on primary key id field in
author table to id field of books table you shall get the following dialogue box:
Figure 9.4
8- click on create button you will get the following relationship diagram:
Figure 9.5
Visual Database Tools
To simplify the development of database applications, Visual Studio 2010 comes with
some visual tools, the most important of which are briefly described in Table9.1 and
then discussed in the following sections.
Query Builder This is a tool for creating SQL queries (statements that
retrieve the data you want from a database or update the
data in the database). SQL is a language in its own right, and
we’ll discuss it later in this chapter. Query Builder lets you
specify the operations you want to perform on the tables of a
database with point-and-click operations. In the background,
Query Builder builds the appropriate SQL statement and
executes it against the database.
Database Designer
And Tables Designer These tools allow you to work with an entire database or its
tables. When you work with the database, you can add new
tables, establish relationships between the tables, and so on.
When you work with individual tables, you can anipulate
the structure of the tables, edit their data, and add
constraints. You can use these tools to manipulate a
complicated object — the database — with point-and-
click operations.
Figure 9.6
Note: Visual Basic Express Edition 2008 limits the data files that are accessible to SQL
Server and Microsoft Access files. Visual Basic Professional Edition enables access to
all data sources. Also VB2010 is best choice.
Very Important Note: if you want Using SQL Server Management Studio
One of the applications installed with SQL Server is SQL Server Management Studio.
To start it, choose Start _ Programs _ SQL Server _ SQL Server Management Studio.
When this application starts, you see the Connect To Server dialog box(as in figure
above). Choose Database Engine in the Server Type field so you can work with
databases on your system. Select the server you want to use in the Server Name field.
Provide your credentials, and click Connect.
click Data menu, then choose show data sources, the data sources window will
appear on the right of the project screen.
Click Data menu, then choose add new data source, dialogue box will appear, click
Database then click Next.
Now if dbauthor.accdb not appears in the Choose Your Data Connection
Screen, then you must click the Newconnection button to specify the database
location that you will use it as datasource in your project(application).
Figure 9.7
Click Yes to add the dbauthor.accdb file to the application’s project folder.
Now Click the Next button to display the Choose Your Database Objects screen. You
use this screen to select the table and/or field objects to include in the dataset, which is
automatically named dbauthorDataSet.
Click the Finish button. The computer adds the dbauthorDataSet to the Data Sources
as shown below
1. Click the form to make it the active window. Click Data on the menu bar and then
click Preview Data to open the Preview Data dialogbox.
2. Click the Preview button. As Figure shown below
Select an object
to preview box
Figure 9.10
Binding the Objects in a Dataset
For the user to view the contents of a dataset while an application is running,
you need to connect one or more objects in the dataset to one or more controls in the
interface. Connecting an object to a control is called binding, and the connected
controls are called bound controls.
A DataGridView control displays the table data in a row and column format, similar
to a spreadsheet. Each row in the control represents a record, and each column
represents a field.
NOTE:also we can use textboxes to binding them to fields of the table without using
DataGridView control.
Data Grid
View control
Text Box
control
Figure 9.11
Drag the authors object from the Data Sources window to the form and then release
the mouse button. The computer adds a DataGridView control to the form, and it binds
the authors object to the control. See Figure below (Result of dragging the
table(authors) object to the form)
Figure 9.12
We see in the bottom of the above window the following threeobjects:
BindingSource object provides the connection between the DataSet and the
bound controls on the form.
tableadapter bindingsource
dataset Bound controls
database on form
tableadaptermanager
Figure 9.13
Moving between records
Example 4
authorsBindingSource.Position = 4
moves the record pointer to the fifth record in the dataset
BindingSource object’s Move methods. The Move methods move the record pointer
to the first, last, next, or previous record in the dataset.
Syntax
bindingSourceName.MoveFirst()
bindingSourceName.MoveLast()
bindingSourceName.MoveNext()
bindingSourceName.MovePrevious()
Example 5
authorsBindingSource.MoveFirst()
.
SQL is a universal language for manipulating data in database tables. Every DBMS
supports it. SQL is a nonprocedural language, which means that SQL doesn’t provide
traditional programming structures such as If statements or loops.
If you are not familiar with SQL, I suggest that you follow the examples in this
experiment and experiment with the sample databases. To follow the examples, you
have two options:
4- SQL Server Management Studio (SSMS) (used with SQL-server).
SSMS helps you manage databases in various ways, including creating
queries to extract data.
5- and Query Designer of Visual Studio. Query Designer is an editor for
SQL statements that also allows you to execute them and see the results.
NOTE: In addition to Query Designer, you can also use Query Builder, which is part
of SSMS and Visual Studio. Query Builder lets you build the statements with visual
tools, and you don’t have to know the syntax of SQL in order to create queries with
Query Builder.
To execute the same queries with Visual Studio, open the Server Explorer window, and
right-click the name of the database against which you want to execute the query. From
the context menu, choose New Query, and a new query window will open.then choose
the table name you want to add then click Add button, finally The Query builder will
appear as in figure shown below.
Diagram pane: displays the tables involved in the query, their fields, and
the relationships between the tables — if any.
Gride Pane: shows the fields that will be included in the output of the query. This
pane is Query Builder, the tool that lets you design queries visually.
the SQL pane, you see the SQL statement produced by the visual tools.
Grid Pane
SQL Pane
Results Pane
Figure 9.14
Now we shall using the authors and books tables of the database dbauthor to execute
the SQL statements.
SELECT query
To retrieve the fields of some table we write
Table 9.2
[] Matches any single character within the brackets. The pattern Santa
[YI]nez will find both Santa Ynez and Santa Inez.
[ ˆ ] Matches any character not in the brackets. The pattern %q[ ˆ u]% will find
words that contain the character q not followed by u (they are misspelled
words).
# Matches any single numeric character. The pattern D1## will find D100 and
D139, but not D1000 or D10.
Example 9: to retrieve all records that authorname field begin with letter A
SELECT * FROM authors WHERE authorname LIKE '%a%'
Example 11: retrieve all records ordered according to the authorname field
SELECT * FROM authors ORDER BY authorname
Example 12: if we assume each author sale 2 books, then to calculate the totalsum
of each edition and put the result in calculated column name it totalsum.
SELECT books.price * 2 AS totalsum FROM books
Calculating Aggregates
SQL supports some aggregate functions, which act on selected fields of all the rows
returned by the query. The basic aggregate functions listed below
Table 9.3
Function Returns
COUNT() The number (count) of values in a specified column
SUM() The sum of values in a specified column
AVG() The average of the values in a specified column
MIN() The smallest value in a specified column
MAX() The largest value in a specified column
Grouping Rows
The GROUP BY clause groups all the rows with the same values in the specified
column and forces the aggregate functions to act on each group separately.
Example 14: if you want sum all prices of books for each author, then the prices
summed according to the grouped ID as following:
SELECT ID, SUM(price) FROM books GROUP BY ID
Example 15: to return all ID’s that have sum(price) more than 100
SELECT ID, SUM(price) FROM books GROUP BY ID HAVING (SUM(price) >
100)
Deleting Rows
The DELETE statement deletes one or more rows from a table; its syntax is as
follows:
NOTE: If the values come from a table, you can replace the VALUES keyword
with a SELECT statement:
INSERT INTO SelectedProducts
SELECT * FROM Products WHERE CategoryID = 4
Editing Existing Rows
The UPDATE statement edits a row’s fields; its syntax is the following:
UPDATE table_name SET field1 = value1, field2 = value2,. . .
WHERE criteria
Example 18:to change the authorname of the authors table where ID=4 (old
value=ahmed, new value=naji)
UPDATE authors SET authorname = 'naji' WHERE (ID = 4)
LINQ Queries
LINQ stands for Language Integrated Query, Perform simple LINQ queries.
Whereas SQL can be used only with database tables, LINQ can be applied to
collections, XML files, and SQL tables. It’s a uniform language for querying data
from several data sources. And it is part of all .NET languages. The LINQ query starts
after the equals sign with the From keyword, which is followed by a variable that
represents the current item in the collection
NOTE: Notice that the syntax does not require you to specify the data type of the
variable in the Dim statement. Instead, the syntax allows the computer to infer the
data type from the value being assigned to the variable, so do this by entering the
Option Infer On statement in the General Declarations section of the Code Editor
window.
Basic LINQ syntax and examples for selecting and arranging records in a dataset
Example 19
Dim records = From authors In DbauthorDataSet.authors Select authors
selects all of the records in the dataset
Example 20
Dim records = From authors In DbauthorDataSet.authors
Order By authors.authorname Select authors
selects all of the records in the dataset and arranges them in ascending order by the
authorname field
Example 21
Dim records = From authors In DbauthorDataSet.authors
Where authors.authorname.ToUpper Like "a*"
Order By employee.title Descending
Select authors
selects from the dataset only the authors records whose name begins with the
letter a, and arranges them in descending order by the title field
authorsBindingSource.DataSource = records.AsDataView
assigns the contents of the records variable to the
authorsBindingSource object
Example 23: To use LINQ to select specific records in the authorname field in the
authors table implement the following program
Figure 9.15
Run the program, if you enter letter ah for example, the result will be all the records
that have the author name begin with ah such as ahmed.
NOTE: Like strFindName & "*", this statement to select any values in field
matching the first letters you enterd.
Using the LINQ Aggregate Operators
LINQ provides several aggregate operators that you can use when querying
a dataset. Th e most commonly used aggregate operators are Average, Count,
Max, Min, and Sum. An aggregate operator returns a single value from a
group of values.
LINQ aggregate operators
Syntax
Dim variableName [As dataType] =
Aggregate elementName In dataset.table
[Where condition]
Select elementName.fieldName
Into aggregateOperator()
Example 24
Dim dblAvgRate As Double =
Aggregate books In dbauthorDataSet.books
Select books.price Into Average()
calculates the average of the prices rates in the dataset and assigns the result to the
dblAvgRate variable
Example 25
Dim intCounter As Double =
Aggregate books In dbauthorDataSet.books
Where books.ID = 2
Select books.title Into Count()
counts the number of authors books editions whose ID number is 2 and assigns the
result to the intCounter variable.
For the changes made to a dataset to be permanent, you need to save the
changes to the database associated with the dataset.
records in a dataset
Syntax
bindingSourceName.Sort = fi eldName
Example 29
TblBooksBindingSource.Sort = "Author"
sorts the records by the Author field
Before deleting any record we must locate the record in the dataset first, thene delete
it.
NOTE: Before deleting the record, the procedure should display a message that asks
the user to confirm the deletion. You will use the MessageBox.Show method to both
display the message and get the user’s response.
Now you will build and save query to invoke it from the visual basic code.
To save query:
Click the Query Builder button to open the Query Builder dialog
box. You will create a parameter query that
allows the user to display the record for specific author.
Write the following SQL statement in the SQL Pane, then click Ok.
Now you will see Method names included in the DataSet Designer window
Figure 9.18
End If
End If
it builds on the older ADO (Active Data Objects) technology. The main goal of
ADO.NET was to enable developers to easily create distributed, data - sharing
applications in the .NET Framework.
ADO.NET provides DataSet and DataTable objects that are optimized for moving
disconnected sets of data across the Internet and intranets, including through firewalls.
At the same time, ADO.NET includes the traditional connection, command, and
DataAdapter objects, as well as an object called a DataReader .Together, these
objects provide the best performance and throughput for retrieving data from a
database.
The basic cycle of data driven applications is (retrieve data from DB , present it to the
user, allow user to edit data, submit changes to DB).
NOTE: All the ADO.NET objects, except the DataTable, are part of the System.Data
namespace. The DataTable is part of System.Xml.
NOTE: for any VB.Net project to add references to any namespaces so that you can
use the namespaces without having to type the full namespace qualifier:right click
Project name, choose Properties to display the Project Properties. Click the References
tab to display the active references for the project, then from the upper list choose any
namespace you want to add to your project then click Add button.
Classes of ADO.NET
To summarize, ADO.NET provides three core classes for accessing databases: the
Connection, Command, and DataReader classes.
Connection class has three derived calasses (SqlConnection, OracleConnection, and
OleDbConnection.)
the Command class has three derived classes: SqlCommand, OracleCommand, and
OleDbCommand.
The OleDbConnection and OleDbCommand classes belong to the OleDb namespace,
which
you must import into your project via the following statement:
Imports System.Data.OleDb
Datareader reading the results of the query returned from database to your
application in a forward-only manner(read rows returned by the query, then close
connection), read-only (you can’t use it to update the underlying rows)
Connecting to a Database
To access data in a database, you must first establish a connection, using an
ADO.NET connection object.
Table 9.4
Parameter Description
Provider The name of the data provider (Jet, SQL,and so on) to use.
Data Source The name of the data source to connect to.
User ID A valid username to use when connecting to the data source.
Password A password to use when connecting to the data source.
Connection class
Imports System.Data.OleDb
Then, Write the following code in the form-load section to setting the
connectionstring property
myConnection.Open()
Important NOTE: if you using office 2003 , then using (OLEDB.11.0) instead of
12.
the Command class, which allows you to execute SQL statements against the
database.
The constructor for an OleDbCommand optionally takes the command to execute
SQL statementst, as well as a connection specifying the datasource
provides the Read method, which advances the current pointer to the next row in the
result set. To read the individual columns of the current row, you use the Itemproperty.
Example 36: the following example is to read the record of specific author, and know
the number of the records in the authors recordset(table).
Figure 9.19
dataFile = "C:\Users\Computer\Documents\dbauthors.accdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
in Find button write
myConnection.Open()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
str = "SELECT * FROM authors WHERE (authorname = '" & TextBox1.Text &
"')"
dr = cm.ExecuteReader
While dr.Read()
TextBox2.Text = dr("ID").ToString
TextBox3.Text = dr("authorname").ToString
TextBox4.Text = dr("title").ToString
End While
myConnection.Close()
cmd.Parameters.Add(NewOleDbParameter("authorname",
CType(TextBox3.Text, String)))
myConnection.Open()
ins = cmd.ExecuteNonQuery()
If ins = 1 Then
MsgBox("added")
End If
myConnection.Close()
str = "Delete from authors Where authorname = '" & TextBox1.Text & "'"
myConnection.Open()
' c.ExecuteNonQuery()
n = c.ExecuteNonQuery
If n <> 0 Then
MsgBox("deleted")
End If
myConnection.Close()
Procedure
2- Repeat previous the previous question with four buttons set their text property
to(First,Next,Last,Previous), and execute the four methods(movefirst,
movenext,….) of the bindingsource.
Discussion
Object
Using Web Browser control to allow the user to surf the internet and open web enabled documents like
html help files.
WebBrowser Control
The VB.NET Windows.Forms.WebBrowser control can be used within applications to allow the user to
surf the internet and open web enabled documents like html help files, word documents etc.
WebBrowser Properties
URL property: Gets or sets the URL of the current Web page. Setting this property navigates the control
to the new URL.
Then run the program When you enter URL address in textbox and click
Go button then click event will fire and navigate method will open website
which URL address is given in TextBox.
Bachgroundworker
If we have an application that has some code that is very time consuming such as large text file parsing
and takes several minutes or longer, you may not want your users to wait till the process is finished.
We can execute this process in a separate thread also known as a worker or secondary thread.
A BackgroundWorker component executes code in a separate dedicated
secondary thread. The BackgroundWorker type in the VB.NET language
is useful for creating a background process, one which won't block the
user interface if it takes a long time to run. In most programs, disk or network
accesses or database accesses and loading huge images are the slowest and
should be put on a background thread if possible.
Methods
BackgroundWorker has two methods, RunWorkerAsync and
CancelAsync. The RunWorkerAsync starts the thread and the
CancelAsync stops the thread.
Events
DoWork This event is fired when the RunWorkerAsync method is called. In this event hander, we
call our code that is being processed inthe background where our application is still doing some other
work. The DoWork event handler looks like this where we need to call our time- consuming method.
Or write in the general declaration of the code window the namespace system.componentmodel
Imports system.componentmodel
Example 2: While BackgroundWorker will be doing some background work, user can still type in the
RichTextBox.
Figure 10.2
BackgroundWorker1.RunWorkerAsync()
End Sub
System.Threading.Thread.Sleep(20000)
Example 3: input just numbers to the textbox, else the error provider icon will
appear
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles TextBox1.TextChanged
If Not IsNumeric(TextBox1.Text) Then
ErrorProvider1.SetError(TextBox1, "Not a numeric value.")
Else
' Clear the error.
ErrorProvider1.SetError(TextBox1, "")
End If
End Sub
Filesystemwatcher
Another very useful class, FileSystemWatcher, acts as a watchdog for file system
changes and raises an event when a change occurs. You must specify a directory to be
monitored. The class can monitor changes to subdirectories and files within the
specified directory. If you have Windows 2000, you can even monitor a remote system
for changes. (Only remote machines running Windows NT or Windows 2000 are
supported at present.)
The option to monitor files with specific extensions can be set using the Filterproperty
of the FileSystemWatcher class. You can also fine-tune FileSystemWatcher to monitor
any change in file Attributes, LastAccess, LastWrite, Security, and Size data.
Event
Use
Name
Changed Fired when a file or directory in the watched path is changed
Created Fired when a file or directory in the watched path is created
Deleted Fired when a file or directory in the watched path is deleted
Fired when the internal buffer overflows due to many changes
Error made over a short time, particularly when the buffer size is
small
Renamed Fired when a file or directory in the watched path is renamed
Process
Example 4:First, here is an example VB.NET program that uses Process.Start to open
the file manager on your C:\ drive. When you run this example the root directoryfolder
will open.
now create module name is module1, and write this code:
Module Module1
Sub Main()
Process.Start("C:\")
End Sub
End Module
Then call the subroutine main in the button click procedure:
Module1.Main()
Example 5: Program that launches web browser [VB.NET], You can tell Windows
to launch a web browser window with a specific URL
Write in the module
Module Module1
Sub openweb()
SearchGoogle("VB.NET awesome")
End Sub
''' <summary>
''' Open the user's default browser and search for the parameter.
''' </summary>
Private Sub SearchGoogle(ByVal t As String)
Process.Start("http://google.com/search?q=" & t)
End Sub
End Module
Write in the click button:
Module1.openweb()
The result is the following window:
Figure 10.3
Serial port
A port, or interface, that can be used for serial communication, in which only 1 bit is
transmitted at a time asynchronously in or out the computer.
A serial port is a general-purpose interface that can be used for almost any type of
device, including modems, mice, and printers, bar code scanners,display prices, And
used in networking.
This code essentially open and closes the serial com port by clicking the button. It
will also change states as in the text on the button will match the current action
that will be allowed. It will also enable or disable the Send Button(added in the
next step) to avoid an illegal operation.
This code snippet functions as the data sending portion of the application and it’ll
log to the ListBox that we will add later.
SerialPort1.WriteLine(TextBox1.Text)
ListBox1.Items.Add("Sent: " + TextBox1.Text)
12. Next, go back to the design view and we will drag and drop a ListBox into
the Form. Resize it as necessary to fit the Form.
Lastly left click once on the SerialPort at the bottom. Then, go to the Properties
pane, click on the lightning symbol. You’ll see Misc, DataReceived,
ErrorReceived, PinChanged. Double click on DataReceived and fill the sub with
this code.
This function will be called whenever there are data stored in the input buffer.
It is to display incoming data from the Serial Communication Port.
15. You’ve completed the coding section. Now press Ctrl-F5 to Start Without
Debugging. The application should run. Test the application by clicking Open
Port, keying in some data in the TextBox and then click Send. Make sure the
Rs232 cable is connected between 2 computers
Service controller
Figure 10.4
Getting all services installed on a machine
ServiceController.GetServices static method returns list of all services running on a
machine. The following code snippet gets all the services and displays them in a
ListBox.
ServiceController Properties
ServiceName - Service name.
DisplayName - Friendly name of a service.
ServiceType - Type of a service such as device driver, process, or kernel.
Status - Status of a service such as running, stopped, or paused.
Example 7: The following code snippet uses some of these properties. Built the
subroutine then call it by the command
Private Sub GetAllServices()
For Each service As ServiceController In ServiceController.GetServices()
Dim serviceName As String = service.ServiceName
Dim serviceDisplayName As String = service.DisplayName
Dim serviceType As String = service.ServiceType.ToString()
Dim status As String = service.Status.ToString()
ListBox1.Items.Add(serviceName + “ “ + serviceDisplayName +
serviceType + “ “ + status)
Next
End Sub
Write in the command button (services):
Call GetAllServices()
After running the program you will get the following:
Figure 10.5
Timer
If you need to execute some code after certain interval of time continuously, you can
use a timer control., you can specify a subroutine to perform the maintenance or
updating code.
NOTE: A Timer control does not have a visual representation and works as a
component in the background.
Timer Properties
Enabled property of timer represents if the timer is running. We can set this property
to true to start a timer and false to stop a timer.
Interval property represents time on in milliseconds, before the Tick event is raised
relative to the last occurrence of the Tick event. One second equals to 1000
milliseconds. So if you want a timer event to be fired every 5 seconds, you need to set
Interval property to 5000.
Dim Timer1 As New Timer()
Timer1.Interval = 2000
Timer1.Enabled = True
Events
If you go to the Events window by clicking little lightning icon, you will see only one
Tick event. Double click on it will add the Tick event handler.
Example 8: if you have a ListBox control on a Form and you want to add some
items to it, like the current dates and times added every some interval
NOTE: set the interval property to 3000 and the enabled property enabled= true.
Private Sub Timer1_Tick(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles Timer1.Tick
ListBox1.Items.Add(DateTime.Now.ToLongTimeString()
+ "," + DateTime.Now.ToLongDateString())
End Sub
List View
The ListView control is used to display a list of items. Along with the TreeView control,
it allows you to create a Windows Explorer like interface.
The ListView control displays a list of items along with icons. The Item property of the
ListView control allows you to add and remove items from it. The SelectedItem
property contains a collection of the selected items. The MultiSelect property allows
you to set select more than one item in the list view. The CheckBoxes property allows
you to set check boxes next to the items.
Rich TextBox control
A RichTextBox control is an advanced text box that provides text editing and
advanced formatting features including loading rich text format (RTF) files.
Maximum Length
You can restrict number of characters in a RichTextBox control by setting MaxLength
property. The following code snippet sets the maximum length of a RichTextBox to
50 characters.
RichTextBox.MaxLength = 50
ReadOnly
RichTextBox.ReadOnly = True
CTRL+Z
CTRL+E
CTRL+C
CTRL+Y
CTRL+X
CTRL+BACKSPACE
CTRL+V
CTRL+DELETE
CTRL+A
SHIFT+DELETE
CTRL+L
SHIFT+INSERT
CTRL+R
RichTextBox class provides SelectAll and DeselectAll methods to select and deselect
all text of a RichTextBox control.
PictureBox control is used to display images in Windows Forms. In this article, I will
discuss how to use a PictureBox control to display images in Windows Forms
applications.
Display an Image
SizeMode
Example 10: uploade picture from any location in the computer by using open
dialogue box control and image property of the picture box.
With OpenFileDialog1
.CheckFileExists = True
.ShowReadOnly = False
.Filter = "All Files|*.*|Bitmap Files (*)|*.bmp;*.gif;*.jpg"
.FilterIndex = 2
If .ShowDialog = DialogResult.OK Then
PictureBox1.Image = Image.FromFile(.FileName)
End If
End With
Example 11:For this tutorial you need a picturebox, a textbox, and abutton.
Button1_Click
NB.Color = Color.FromArgb(128, 0, 0, 0)
Figure 10.7
LinkLabel control
A LinkLabel control is a label control that can display a hyperlink. You can make link
to web page
System.Diagnostics.Process.Start("http://www.google.com")
You can use the LinkLabel almost like a button by simply putting any code you like
in the LinkClicked event instead of the Start method.
Procedure
1- Add multiple columns to listview control, then add content to one rowof the control
2- Repeate the previous example but by using textboxes to add items to
listview control.
Discussion
REFERENCES
1- Clearly Visual Basic, DIANE ZAK, Second Edition, 2010
4- Sams teach yourself Visual Basic 2010 in 24 hours complete :starter kit /
James Foxall. Library of Congress Cataloging-in- Publication Data: Foxall,
James D.