Programming in VB Unit 2
Programming in VB Unit 2
Unit 2
1. Define event? Give two examples of event
in visual basic?
4. Mouse Up: occurs when the user releases the mouse button
1) Got Focus: It can be used to validate the data entered by the user.
2) Lost Focus: when focus moves from one object to the another, the
first object which had the focus receives the lost Focus,
3) Set Focus: Focus can also be moved to another object by using the
set focus method in the code.
4) Tab order: Tan key can be used to move focus from one object to
another
2) What is Variables? How to declare variables in VB
• Variables are used to store values during execution of a program.
• They take different values at different time.
• They can access the value of the variable by using there variable name.
RULES:
1)Variable names must begin with a letter, digits or both
2)No special characters are allowed except underscore ( _ ) eg: tot_marks
3)VB is not case sensitive
4)Appropriate variable name must be chosen to indicate their role in the program
5)Max length should not exceed 255 characters.
Declaring variables
• Multiple variable can be declared as: • Variant : can store all type of data values &
its extremely flexiable
Dim num1 As Integer,Num2 As Integer
Eg: Dim myval
2) Byte Data Type : None of the numeric data type cant store in a single bytes
Byte datatype stores an integer range of 0 to 255
Eg: Dim n1 As byte
n1 = 25
3) String Variable:- Can store text/string of characters with double quotes “ ”
Eg: “new_Horizon”
• Variant : can store all type of data values & its extremely flexiable
[grade<60]
If grade >= 60
Then
Textbox1 = “A”
End if
sts1
20
If … Then … Else
If condition 1 Then
Sts block – S1
ElseIf conditions 2 Then
Sts block – S2
EndIf
S3
Dim n As integer
N = val(textnum)
Select Case n
Case 1
Lblname = “Sunday”
Case 2, 3, 4, 5
Lblname = “Working Days”
Case 6,7
Lblname = “week end”
Case else
Lblname = “wrong Entry”
End select
End sub
Select … Case Select Case grade
Case 100
Case 75 To 100
Select Case expression Text10.Text = "A"
Case Val1
Case 60 To 74
S1 Text10.Text = "B"
Case Val2
Case 50 To 69
S2 Text10.Text = "C"
…….
Case Valn Case 40 To 49
Text10.Text = "D"
sn
Case Else Case Else
Text10.Text = "F"
Sd
End Select End Select
Private Sub Command1_Click()
Dim s1, s2, s3, s4, s5, tot_mar As Integer
Dim per As Single
Dim grade As String
s1 = Val(Text3.Text)
s2 = Val(Text4.Text)
s3 = Val(Text5.Text)
s4 = Val(Text6.Text)
s5 = Val(Text7.Text)
tot_mar = s1 + s2 + s3 + s4 + s5
Text8.Text = tot_mar
per = tot_mar / 5
Text9.Text = per
If per >= 75 Then
Text10.Text = "A"
ElseIf per >= 60 And per < 75 Then
Text10.Text = "B"
ElseIf per >= 50 And per < 60 Then
Text10.Text = "C"
ElseIf per >= 40 And per < 50 Then
Text10.Text = "D"
Else
5. Looping Structures / Control Structures
• Loops are required whenever a set of statements must be executed a number
of times.
• Control structures can be classified into 2 categories:
1. Entry – Controlled Loops
2. Exit – Controlled Loops
Entry Controlled Loops checks the control condition before entering the loop.
The body of the loop is executed only when the condition is true.
Otherwise, the control is transferred to next statement outside the loop.
The loop is executed repeatedly until the control condition becomes false.
Exit – Controlled Loops test the control condition at the end of the body of the
loop. The body of the loop is executed at least once, since the condition is
tested only at the end of the loop.
The looping statement will be executed repeatedly until the control condition is
false. Entry Controlled Exit - Controlled
Do While Condition Do
Statements Statements
Loop Loop While Condition
Do Until Condition Do
Statement Statement
Loop Loop Until Condition
While Condition
Statement
Wend
For Index = Start To End
Statements
Next
For Each element in group
Statement
Next
Do While Condition
Statements
Loop
• The condition is checked first
• If true the sts are executed and control is transferred back to the Do-while sts.
• When the condition is False, sts in the body are skipped and control is transferred to the next sts outside the
loop
• Its entry controlled loop
Do while M <> N
if M > N then
M=M–N
Else
N=N–M
End If
Loop
Do
Statements
Loop While Condition
It is exit controlled loop.
The sts are executed first and only then the condition is tested
Therefore the statements are executed at least once.
The loop is executed as long as the condition is fasle.
Dim M As Integer, N As Integer
M=12 : N=16
Do
if M > N then
M=M–N
Else
N=N–M
End If
Loop while M <> N
Do until Condition
Statement
Loop
While M <> N
If M > N Then
M = M–N
Else
N = N–M
End If
Wend
GCD = N
Text3.Text = GCD
End Sub
For Index = Start To end
statement
Next
End Sub
6. Explain InputBox() and MsgBox() functions in
Visual Basic
INPUT BOX
• Displays a prompt in a dialog box
• Waits for the user to input text or click a button
• and returns a String containing the contents of the text box.
Syntax :
Command Button
The general Form of InputBox Function
Variable Name = InputBox(prompt [,Title] [,Default] [x pos] [,y pos])
Call Big(N1, N2, N3) ‘ Calls the procedure Big passing the value of
N1, N2, N3 as argument
0 – none VbBSNone
1- fixedsingle vbFixedSingle (form has a border, but cannot
be resized. Its fixed
2 – sizable vbsizable consists of a border and title bar
Label Properties:
Autosize : Can be set to true or false. When true it allows the label to
automatically resize itself to display its entire contents.
BackStyle: Can be set to
0 – Transparent or 1 – opaque
backStyle of labels set transparent, so that the text appears
to be placed directly on the Form.
Command Button
its frequently used control.
Its used to invoke response from the user.
4) Picture: a picture can be add in the Command button and it will be displayed
only when the style property is set to graphical.
7) TabIndex : Tab Index value starting from 0 sets the order in which focus is
received by the control on a form. When one of the values of Tab Index is altered
the rest of the value are automatically re-ordered.
Most frequently used Event procedure for command
Button are:
• Click
• KeyDown
• Keypress
• keyUp
• MouseDown
• MouseMove
• MouseUp
• GotFocus
• LostFocus
TextBox Control
• Its used to enter the text in a windows user interface
2) Locked: indicates whether the user can type in the textbox or not
6)ScrollBars: Indicates either Horizontal Scrollbars or both for the textbox, this
property is used with multiline property.
• SetFocus
• Change
• Click
• Gotfocus
• Lostfocus
• Keypress
Option Button
control allows the user to select only one option from a group of options on a form.
If the user wants to select 2 options within a form, the option must be grouped together
within a frame control
• Option Button Properties
1) Name: set the name of the
option button
2) Caption: determines the
purpose of the option button
3) Value: true or false.
set true at design time –
pre selection at run time.
CheckBox Control:
A check box control is commonly used to express optional features.
If checked, the feature is used.
If unchecked, the feature is not used
• Multiple optional can be selected
More than one option can be checked In a group only one option can be selected
Private Sub Command1_Click() If Option4.Value = True Then
If Option1.Value = True Then Label1.Caption = Label1.Caption + "
and ice cream"
Label1.Caption = "apple"
ElseIf Option5.Value = True Then
ElseIf Option2.Value = True Then Label1.Caption = Label1.Caption + "
Label1.Caption = "orange" and sweets"
End Sub
Private Sub Command2_Click()
If Check1.Value = vbChecked Then If Check1 = 0 And Check2 = 0 And
Label2.Caption = Label2.Caption + "happy" Check3 = 0 Then
End If Label2.Caption = Label2.Caption
+ " None is selected"
If Check2.Value = vbChecked Then End If
Label2.Caption = Label2.Caption + "sad"
End Sub
End If
End If
VB provides 2 ways of displaying pictures on the
screen are:
• Picture Box
• Image Box
Picture box control
• Are used to display graphics pictures during the design time from the
property window picture.
• Picture box occupies more space.
Properties are:
• Name : identifies the name of the picture box
• Picture: load the picture during the design time.. Location of the
image
• Autosize: when its true, the picturebox is automatically resized to
display the entire content else
when false, only the part of the entire picture will be displayed.
• Picture box uses PaintPicture
• Paint Picture: used to draw the content of a picturebox control into
another picturebox
• Syntax :
Picturebox.paintpicture picturename,x1,y1,w1,h1,x2,y2,w2,h2
Image Box Control
• With the main application, you can maintain multiple open windows,
but not multiple copies of the application. Data exchange is easier
when you can view and compare many documents simultaneously.
MDI Applications
• You can use three different types of forms in an MDI application
• An MDI parent form acts as the container for the MDI child forms in the solution
• An MDI child form always appears inside the visible region of its MDI parent
form
• A project may have one or more MDI child forms
• Standard forms can be displayed anywhere on the screen and are not contained
by the MDI parent form (SDI Single document interface)
• Standard forms are typically displayed as dialog boxes
• An MDI application must have at least two Form, the parent Form and
one or more child Forms. Each of these Forms has certain properties.
There can be many child forms contained within the parent Form, but
there can be only one parent Form.
• The parent Form may not contain any controls. While the parent
Form is open in design mode, the icons on the ToolBox are not
displayed, but you can't place any controls on the Form. The parent
Form can, and usually has its own menu.
To create an MDI application, follow these steps:
• Start a new project and then choose Project Add MDI Form to add
the parent Form.
• Set the Form's caption to MDI Window
• Choose Project Add Form to add a SDI Form.
• Make this Form as child of MDI Form by setting the MDI Child
property of the SDI Form to True. Set the caption property to MDI
Child window.
MDI Form cannot contain objects other
than child Forms, but MDI Forms can
have their own menus
At design time double click on MDI Open and add the following
code in the click event of the open menu.
Form1.Show
And so double click on MDI Exit and add the following code in the
click event
End
Combo Box control
• Combo box control which is a combination of a textbox with a short dropt-
down list
Personal Info
Payments
Student Database
Grades
Structure of a Database
• Tables – collection of related information
• Records –single piece of information
• Fields – smallest unit of information that is useful
to users.
Structure of a Database
Record
Name:
Address:
Contact No.:
Fields
Table
Primary Key
Foreign key
Eg: cust_no in Invoice Table is the foreign key. The same value of
the cust_no in the customer table is the primary key
Visual Basic and Database
1) Connection
2) Command
3) Record Set
The other dependent objects are:
4)Parameter
5)Field
6)Error and
7)Property
Connection
• The connection object is the top-level object which represents a
unique connection with a data source.
• The connection of the object to access the required records from
database or to update the database.
PROPERTIES:
1) ConnectionString : Contains information used to establish a
connection to a data source. It sets or returns a string value
2) Mode: specifies the available permissions for modifying data in a
connection
• adModeRead : Indicates read only permission.
• adModewrite : Indicates write only permission.
• adModeReadWrite : Indicates both read and write permissions.
errmsg:
MsgBox "Error in saving Data"
End Sub
Parameter
• Data retrieval command can be used repeatedly by varying the
parameter values each time, to retrieve specific information.
A string
The user Optional
containing The
name at the If the value is set
information Password
time of the to
at the time
required to connection adConnectAsync,
of the
establish a is this connection
connection
connection to a establishing will be opened
is
datasource establishing asynchronously
Property
• Every ADO object has a set of unique properties that describes the
behaviour of the object
• ADO objects consist of two type of properties:
1) built-in : Properties are part of the ADO object and are always
available.
2) Dynamic: properties are normally added to the objects properties
collection by the provider and exit only while that provider is being
used.
Eg: MyObject.Properties (0)
Using the SQL Statements
<adodc name>.RECORDSET.<method>
The Name of the adodc object Refers to the table Methods that can
object be done to a table
Types of ADODC methods
• Record Operations
• Addnew – used to add records to the table.
• Delete – used to delete records from the table.
• Update – used to save records to the table.
• CancelUpdate – cancels any record-related operations.
Types of ADODC commands
• Record Navigation
• Find <parameters> - used to find or search records,
based on key fields.
• Movefirst – go to the first record.
• Movelast – go to the last record.
• Movenext – go to the next record.
• Moveprevious – go to the previous record.
• Move(record no.) – go to a specified record no.
Types of ADODC commands
• Record Counters
• RecordCount – returns the number of records on the
table
• EOF – End of File, returns True if the record pointer
reaches the end of the table.
• BOF – Beginning of File, returns True if the record
pointer reaches the beginning of the table
Finding Records
adoSTUD.REFRESH
adoSTUD.RECORDSET.FIND “[LName] like ‘Locsin’”