Вы находитесь на странице: 1из 42

lOMoARcPSD|3433744

Unit-4- Notes FOR Visual Basic PART 4

Visual Programming (Bangalore University)

StuDocu is not sponsored or endorsed by any college or university


Downloaded by Manoj BE (manojporsche24@gmail.com)
lOMoARcPSD|3433744

 
NOTES FOR VISUAL BASIC PART 4
 
 
USING CONTROL ARRAY
A control array is group of controls that share same name and type. A control
array has at least one element and can grow up to 32767 elements. The
elements of the same control array may have their own property settings
The control arrays are useful for following things:
control arrays use fewer resources than multiple controls of same type.
code can be shared among the elements of a control array.

Note: all option button has name option1 and index ranging from 0 to 5. first
three are placed inside frame1 and last three are placed inside frame2.
Private Sub Command1_Click()
Dim ord$
Dim i%
For i = 0 To 2
If Option1(i).Value = True Then
ord = ord + Option1(i).Caption
End If
Next

ord = ord + " & "

For i = 3 To 5
If Option1(i).Value = True Then
ord = ord + Option1(i).Caption
End If
Next
MsgBox "Your Order is=" + ord

Downloaded by Manoj BE (manojporsche24@gmail.com)


lOMoARcPSD|3433744

End Sub

Example-2

Note: all checkboxes have name check1 and index ranging from 0 to 5.
Private Sub Command1_Click()
Dim ord$
Dim i%
ord = "beverage="
For i = 0 To 2
If Check1(i).Value = 1 Then
ord = ord + Check1(i).Caption + ","
End If
Next

ord = ord + "food items="

For i = 3 To 5
If Check1(i).Value = 1 Then
ord = ord + Check1(i).Caption + ","
End If
Next

ord = Left(ord, Len(ord) - 1)


MsgBox "Your Order is=" + ord
End Sub

Private Sub Command2_Click()


End
End Sub

Downloaded by Manoj BE (manojporsche24@gmail.com)


lOMoARcPSD|3433744

LISTBOX

list box is useful to give several choices to the user and user can select one or
more choices.
following are the common properties of text box control:
name, height, width, left, top
list: it is an array. It contains name of the item in the list box.
listindex: it gives index of the item selected, if no item is selected then it’s value
is -1.
listcount: gives no. of items in list.
newindex: gives the index given to the item newly added to list box(useful if
sorted is true).
sorted: if true items are sorted alphabetically.
style:can be standard or checkbox.
multiselect: if true more than one items can be selected..
itemdata: it is an array. No. of elements is equal to no. of items in listbox. You
can store any integer value for each item.
selected: it is an array. It contains value true if an item is selected otherwise
contains false( useful if multiselect is true)
Methods:
additem : to add new item in list box
removeitem: to remove item from list whose index is given as argument.
clear: delete all items.
Event:
Click, dblclick.

Example-1

Private Sub Command1_Click() 'add item in list


If Len(Trim(Text1)) > 0 Then 'check for textbox emptiness
List1.AddItem Text1.Text
Text1 = ""
Text1.SetFocus
End If
End Sub

Downloaded by Manoj BE (manojporsche24@gmail.com)


lOMoARcPSD|3433744

Private Sub Command2_Click() 'remove item from list


If List1.ListIndex <> -1 Then 'make sure item is selected
List1.RemoveItem List1.ListIndex
End If

End Sub

Private Sub Command3_Click()


End
End Sub

Private Sub Form_Load()


List1.AddItem "Apple"
List1.AddItem "Mango"
List1.AddItem "Banana"
List1.AddItem "Pineapple"
List1.AddItem "Guava"
End Sub

Example-2

Private Sub Command1_Click(Index As Integer)


Select Case Index
Case 0
If List1.ListIndex <> -1 Then
'add selected item from list1 to list2
List2.AddItem List1.List(List1.ListIndex)
'remove selected item from list1
List1.RemoveItem List1.ListIndex
End If

Downloaded by Manoj BE (manojporsche24@gmail.com)


lOMoARcPSD|3433744

Case 1
If List2.ListIndex <> -1 Then
'add selected item from list2 to list1
List1.AddItem List2.List(List2.ListIndex)
'remove selected item from list2
List2.RemoveItem List2.ListIndex
End If
Case 2
For i = 0 To List2.ListCount - 1

List1.AddItem List2.List(i)
Next
List2.Clear

Case 3

For i = 0 To List1.ListCount - 1

List2.AddItem List1.List(i)
Next
List1.Clear
End Select
End Sub

Private Sub Form_Load()


‘ we could have added items in list box using list property from properties
window
List1.AddItem "Apple"
List1.AddItem "Orange"
List1.AddItem "Banana"
List1.AddItem "PineApple"

Downloaded by Manoj BE (manojporsche24@gmail.com)


lOMoARcPSD|3433744

End Sub

Example-3

‘Working with multiselect to extended

Private Sub Command1_Click(Index As Integer)


Select Case Index
Case 0
For i = List1.ListCount - 1 To 0 Step -1
'add selected item from list1 to list2
If List1.Selected(i) = True Then
List2.AddItem List1.List(i)
List1.RemoveItem i
End If
Next

Case 1
For i = List2.ListCount - 1 To 0 Step -1
'add selected item from list1 to list2
If List2.Selected(i) = True Then
List1.AddItem List2.List(i)
List2.RemoveItem i
End If
Next
Case 2
For i = 0 To List2.ListCount - 1

List1.AddItem List2.List(i)
Next
List2.Clear

Downloaded by Manoj BE (manojporsche24@gmail.com)


lOMoARcPSD|3433744

Case 3

For i = 0 To List1.ListCount - 1

List2.AddItem List1.List(i)
Next
List1.Clear
End Select
End Sub

Private Sub Form_Load()


List1.AddItem "Apple"
List1.AddItem "Orange"
List1.AddItem "Banana"
List1.AddItem "PineApple"

End Sub

COMBO BOX
combo box is useful to give several choices to the user and user can select only
one choice. Combo box is combination of textbox and drop down list.
following are the common properties of text box control:
name, height, width, left, top
list: it is an array. It contains name of the item in the list box.
listindex: it gives index of the item selected, if no item is selected then it’s value
is -1.
listcount: gives no. of items in list.
newindex: gives the index given to the item newly added to list box(useful if
sorted is true).
sorted: if true items are sorted alphabetically.
style: drop down combo, simple list and drop down list.

Downloaded by Manoj BE (manojporsche24@gmail.com)


lOMoARcPSD|3433744

itemdata: it is an array. No. of elements is equal to no. of items in listbox. You


can store any integer value for each item.
text:gives the text in text portion of combo box
locked: if true text can’t be altered in textbox portion
Methods:
additem : to add new item in list box
removeitem: to remove item from list whose index is given as argument.
clear: delete all items.
Event:
Click, dblclick

Example-1

Private Sub Command1_Click() 'add item in list


If Len(Trim(Combo1)) > 0 Then 'check for textbox emptiness
Combo1.AddItem Combo1.Text
Combo1.Text = ""
Combo1.SetFocus
End If
End Sub

Private Sub Command2_Click() 'remove item from list


If Combo1.ListIndex <> -1 Then 'make sure item is selected
Combo1.RemoveItem Combo1.ListIndex
End If

End Sub

Private Sub Command3_Click()


End
End Sub

Downloaded by Manoj BE (manojporsche24@gmail.com)


lOMoARcPSD|3433744

Private Sub Form_Load()


Combo1 = ""
Combo1.AddItem "Apple"
Combo1.AddItem "Mango"
Combo1.AddItem "Banana"
Combo1.AddItem "Pineapple"
Combo1.AddItem "Guava"
End Sub

Creating Menu

Private Sub Form_Load()


Text1.Text = ""
If Len(Clipboard.GetText) > 0 Then
mnueditPaste.Enabled = True
Else
mnueditPaste.Enabled = False
End If
If Len(Text1.SelText) > 0 Then
mnueditcut.Enabled = True
mnueditcopy.Enabled = True
Else
mnueditcut.Enabled = False
mnueditcopy.Enabled = False
End If
End Sub

Private Sub mnueditcopy_Click()


Clipboard.SetText Text1.SelText
mnueditPaste.Enabled = True
End Sub

Downloaded by Manoj BE (manojporsche24@gmail.com)


lOMoARcPSD|3433744

Private Sub mnueditcut_Click()


Clipboard.SetText Text1.SelText
Text1.SelText = ""
mnueditPaste.Enabled = True
mnueditcut.Enabled = False
mnueditcopy.Enabled = False
End Sub

Private Sub mnueditPaste_Click()


'we can not write text1.text=clipboard.gettext otherwise
'it will replace all the text of textbox
Text1.SelText = Clipboard.GetText
mnueditcut.Enabled = False
mnueditcopy.Enabled = False
End Sub

Private Sub mnufileExit_Click()


'prompt for asking file name and saving the file should go here
End Sub

Private Sub mnufilenew_Click()


Dim f As New Form1
f.Show
f.Text1 = ""
End Sub

Private Sub Text1_KeyUp(KeyCode As Integer, Shift As Integer)


If Len(Text1.SelText) > 0 Then
mnueditcut.Enabled = True
mnueditcopy.Enabled = True
Else
mnueditcut.Enabled = False
mnueditcopy.Enabled = False

Downloaded by Manoj BE (manojporsche24@gmail.com)


lOMoARcPSD|3433744

End If
End Sub

Private Sub Text1_MouseUp(Button As Integer, Shift As Integer, X As Single, Y As


Single)
If Len(Text1.SelText) > 0 Then
mnueditcut.Enabled = True
mnueditcopy.Enabled = True
Else
mnueditcut.Enabled = False
mnueditcopy.Enabled = False
End If
End Sub

Example-2

Private Sub eo1_Click()


Text3 = Val(Text1) * Val(Text2)
End Sub

Private Sub eo2_Click()


Text3 = Val(Text1) / Val(Text2)
End Sub

Private Sub so1_Click()


Text3 = Val(Text1) + Val(Text2)
End Sub

Private Sub so2_Click()


Text3 = Val(Text1) - Val(Text2)
End Sub

Downloaded by Manoj BE (manojporsche24@gmail.com)


lOMoARcPSD|3433744

Scrollbar: this control is useful to let the user select value within a range.
Properties are as follows:
max: maximum value of the range
min: minimum value of the range
smallchange: when user clicks on either arrow value property will change by this
quantity.
largechange: when user clicks on either side of the thumb, value property
change by this quantity.
value: gives thumb position
Events:
change: when clicked on arrow or on either side of thumb.
scroll: when thumb is moved by mouse.
There are two types of scroll bars vertical and horizontal.

Private Sub Form_Load()


HScroll1.Min = 0
HScroll1.Max = 255
HScroll1.SmallChange = 5
HScroll1.LargeChange = 10

HScroll2.Min = 0
HScroll2.Max = 255
HScroll2.SmallChange = 5
HScroll2.LargeChange = 10

HScroll3.Min = 0
HScroll3.Max = 255
HScroll3.SmallChange = 5
HScroll3.LargeChange = 10

Downloaded by Manoj BE (manojporsche24@gmail.com)


lOMoARcPSD|3433744

End Sub

Private Sub HScroll1_Change()


Text1.BackColor = RGB(HScroll1, HScroll2, HScroll3)
Label1.Caption = "r=" + CStr(HScroll1) + "," + "g=" + CStr(HScroll2) + "," + "b=" +
CStr(HScroll3)
End Sub
Private Sub HScroll2_Change()
Text1.BackColor = RGB(HScroll1, HScroll2, HScroll3)
Label1.Caption = "r=" + CStr(HScroll1) + "," + "g=" + CStr(HScroll2) + "," + "b=" +
CStr(HScroll3)
End Sub
Private Sub HScroll3_Change()
Text1.BackColor = RGB(HScroll1, HScroll2, HScroll3)
Label1.Caption = "r=" + CStr(HScroll1) + "," + "g=" + CStr(HScroll2) + "," + "b=" +
CStr(HScroll3)

End Sub
Private Sub HScroll1_scroll() 'moving thumb using mouse changes color
immediately
Text1.BackColor = RGB(HScroll1, HScroll2, HScroll3)
Label1.Caption = "r=" + CStr(HScroll1) + "," + "g=" + CStr(HScroll2) + "," + "b=" +
CStr(HScroll3)
End Sub
Private Sub HScroll2_scroll()
Text1.BackColor = RGB(HScroll1, HScroll2, HScroll3)
Label1.Caption = "r=" + CStr(HScroll1) + "," + "g=" + CStr(HScroll2) + "," + "b=" +
CStr(HScroll3)
End Sub
Private Sub HScroll3_scroll()
Text1.BackColor = RGB(HScroll1, HScroll2, HScroll3)
Label1.Caption = "r=" + CStr(HScroll1) + "," + "g=" + CStr(HScroll2) + "," + "b=" +
CStr(HScroll3)

End Sub

Downloaded by Manoj BE (manojporsche24@gmail.com)


lOMoARcPSD|3433744

Timer control
Timer control is useful to execute some code at regular interval of time.
Properties:
interval: set duration in millisecond
enabled: if true timer control can fire event
event:
timer: this event is fired at regular interval as specified in interval property.

Private Sub Form_Load()


Timer1.Interval = 300
End Sub

Private Sub Timer1_Timer()


Label1.ForeColor = RGB(255 * Rnd, 255 * Rnd, 255 * Rnd)
End Sub

Drive, directory and file controls


Drive control displays drives available in computer. Directory displays list of
directory and file list box displays files in currently selected directory.

Drive control property:


drive: gives name of the drive
directory control property:
path: gives path of the currently selected directory.

File control property:


filename: gives name of the file selected.
path: gives path of the file

Downloaded by Manoj BE (manojporsche24@gmail.com)


lOMoARcPSD|3433744

events:
change: for drive and directory
click: for file list box.

Private Sub Dir1_Change()


File1.Path = Dir1.Path
End Sub

Private Sub Drive1_Change()


Dir1.Path = Drive1.Drive
End Sub

Private Sub File1_Click()


On Error Resume Next
Picture1.Picture = LoadPicture(Dir1.Path + "\" + File1.FileName)
End Sub

Private Sub Form_Load()


File1.Pattern = "*.*"
End Sub

Shape control.
Shape control is useful to draw various figures on form. It doesn’t fire any event.
Properties:
1.backcolor
2. Borderstyle: you can have different line types.
3. borderwidth: if you set border width other than 1 then you can not have
different border style.
4. fillcolor: color for the pattern used for fill
5. fillstyle: you can choose different fill pattern.

Downloaded by Manoj BE (manojporsche24@gmail.com)


lOMoARcPSD|3433744

6. shape: controls type of shape


0 for rectangle
1 for square
2 for oval
3 for circle
4 for rounded rectangle
5 for rounded square

Example-1

Private Sub Combo1_Click()


If Combo1.ListIndex <> -1 Then
Shape1.Shape = Combo1.ListIndex
End If
End Sub

Private Sub Combo2_Click()


If Combo2.ListIndex <> -1 Then
Shape1.BorderStyle = Combo2.ListIndex
End If
End Sub
Private Sub Combo3_Click()
If Combo3.ListIndex <> -1 Then
Shape1.FillStyle = Combo3.ListIndex
End If
End Sub
Private Sub Form_Load()
Shape1.FillColor = vbBlue
Shape1.BorderColor = vbRed
Combo1.AddItem "rectangle"
Combo1.AddItem "square"
Combo1.AddItem "circle"
Combo1.AddItem "oval"

Downloaded by Manoj BE (manojporsche24@gmail.com)


lOMoARcPSD|3433744

Combo1.AddItem "rounded rectangle"


Combo1.AddItem "rounded square"

Combo2.AddItem "transparent"
Combo2.AddItem "solid"
Combo2.AddItem "dash"
Combo2.AddItem "dot"
Combo2.AddItem "dash-dot"
Combo2.AddItem "dash-dot-dot"
Combo2.AddItem "inside solid"

Combo3.AddItem "solid"
Combo3.AddItem "transparent"
Combo3.AddItem "horizontal line"
Combo3.AddItem "vertical line"
Combo3.AddItem "upward diagonal"
Combo3.AddItem "downward diagonal"
Combo3.AddItem "cross"
Combo3.AddItem "diagonal cross"
End Sub

Line Control
Useful to draw line on form

Image Control
This control is useful to display image. It has following properties
picture: set this property to any picture file.
stretch: if true picture is resized to fill in image control
Event
Click

Downloaded by Manoj BE (manojporsche24@gmail.com)


lOMoARcPSD|3433744

Write short notes on data control.


VB provides a very useful control called data control that lets you access data
coming from a database. You can perform most data access operations using
data control without writing any code at all. The data control enables you to
move from record to record and to display and manipulate data from the records
coming from. Data control is collection of connection and recordset objects and
it is based on data access object library(DAO).
Following are the properties which are quite commonly used:
databasename: determines the path and filename of the database file.
exclusive: if this property is set to true, then when you open the database only
you will have exclusive access to the database and others can’t access the
database.
options: determines access constraints for the tables you are working on.
readonly: when true, you can not update the database.
recordsource: determines the source of the set of records retrieved by the data
control.

Using data control to access data in a database

place data control, labels and text boxes on form and set following properties for
data control
databasename:name of the database you want to work on e.g.
C:\Documents and Settings\COMPAQ\My Documents\emp.mdb
recordsource: select the table you want to work on e.g.
emplist
for each text box in form set datasource to data1 then set datafield to the field
whose data the textbox should display.
then set caption for labels.

Write short notes on RDO control.


VB provides a very useful control called RDO data control that lets you access
data coming from a database. You can perform most data access operations

Downloaded by Manoj BE (manojporsche24@gmail.com)


lOMoARcPSD|3433744

using data control without writing any code at all. The data control enables you
to move from record to record and to display and manipulate data from the
records coming from. RDO control is collection of connection and resultset
objects and it is based on Remote Data Access object library(RDO).
Following are the properties which are quite commonly used:
datasourcename: dsn contains the path and filename of the database file and
database driver to use for database access.
sql: determines the source of the set of records retrieved by the RDO data
control.

Using RDO control to access data in a database

To bring RDO control in toolbox follow these steps:


Use project->components->tick mark Microsoft remote data control 6.0 option
then click on OK.

To create DSN follow these steps:


Start->control Panel->administrative tools->data sources->click on system dns
tab ->click on add command button ->select Microsoft access driver(*.mdb and
click on finish command button )-> specify data sourcename e.g. empdsn then
Click on select command button and select the database you want to work on
e.g.
C:\Documents and Settings\COMPAQ\My Documents\emp.mdb->ok->Ok

place RDO data control, labels and text boxes on form and set following
properties for data control
datasourcename:select the dsn created earlier
e.g. empdsn
sql: select the table using sql statement you want to work on
e.g. select * from emplist
for each text box in form set datasource to msrdc1 then set datafield to the field
whose data the textbox should display.
then set caption for labels.

Downloaded by Manoj BE (manojporsche24@gmail.com)


lOMoARcPSD|3433744

Write short notes on ADO control.


VB provides a very useful control called ADO data control that lets you access
data coming from a database. You can perform most data access operations
using data control without writing any code at all. The data control enables you
to move from record to record and to display and manipulate data from the
records coming from. ADO control is collection of connection and recordset
objects and it is based on ActiveX Data Access object library(ADO).
Following are the properties which are quite commonly used:
connectionstring: dsn contains the path and filename of the database file and
database driver to use for database access you can specify dsn in connection
string if you select ODBC data source name radio button..
recordsource: determines the source of the set of records retrieved by the ADO
data control.

Using ADO control to access data in a database

To bring ADO control in toolbox follow these steps:


Use project->components->tick mark Microsoft ADO Data Control 6.0(OleDB)
option then click on OK.

To create DSN follow these steps:


Start->control Panel->administrative tools->data sources->click on system dns
tab ->click on add command button ->select Microsoft access driver(*.mdb and
click on finish command button )-> specify data sourcename e.g. empdsn then
Click on select command button and select the database you want to work on
e.g.
C:\Documents and Settings\COMPAQ\My Documents\emp.mdb->ok->Ok

place ADO data control, labels and text boxes on form and set following
properties for data control
connectionstring :select ODBC data source name radio button and select dsn
created earlier
e.g. empdsn
recordsource: select command type adcmdtable from first combo box and select
the name of table from second combo box then click on ok

Downloaded by Manoj BE (manojporsche24@gmail.com)


lOMoARcPSD|3433744

e.g emplist
or select command type adcmdtext from first combo box and specify sql
statement in text box

for each text box in form set datasource to adodc1 then set datafield to the field
whose data the textbox should display.
then set caption for labels.
Data Form Wizard
Data form wizard is a tool using which we can make data entry form quickly.
Following are the steps required to build data form wizard:
Project->add form->vb data form wizard->Open->

Using Datagrid control.


We can use data grid control to add, edit, delete and view records. One record is
shown in one row.
Useful properties:
datasource: set ado control to this property
allowaddnew: if true new record can be added
allowdelete: existing record can be deleted
allowupdate:existing record can be updated

To create DSN follow these steps:


Start->control Panel->administrative tools->data sources->click on system dns
tab ->click on add command button ->select Microsoft access driver(*.mdb and
click on finish command button )-> specify data sourcename e.g. student then
Click on select command button and select the database you want to work on
e.g.
C:\Documents and Settings\COMPAQ\My Documents\student.mdb->ok->Ok

To bring ADO control and data grid control in toolbox follow these steps:
Use project->components->tick mark Microsoft ADO Data Control 6.0(OleDB)
option then click on OK.

Downloaded by Manoj BE (manojporsche24@gmail.com)


lOMoARcPSD|3433744

place ADO data control, and datagrid on form and set following properties for
data control
connectionstring :select ODBC data source name radio button and select dsn
created earlier
e.g. student
recordsource: select command type adcmdtable from first combo box and select
the name of table from second combo box then click on ok
e.g student
or select command type adcmdtext from first combo box and specify sql
statement in text box

set datasource property of datagrid to adodc1 data control.


if you want to add, edit, delete record set allowaddnew, allowdelete,
allowupdate for datagrid.

Using Datalist/data combo grid control.


We can use data combo control to display field content of one table and store
content of another field inside other table.
Suppose there are two tables as follows:
Student Table

Studentname Rollno Class address

Rahul 101 Bsc-i New shanti nagar

Mukesh 102 Bsc-2 New shanti nagar

Anjani 103 Bsc-1 Purani basti

Downloaded by Manoj BE (manojporsche24@gmail.com)


lOMoARcPSD|3433744

Sudhir 104 Bsc-2 Choubey colony

Test Table

Rollno Phy chem Maths

101 80 45 77

102 70 55 56

103 67 77 85

104 55 65 89

Useful properties:
datasource: set adodc1 control to this property
datafield: set adodc1 control to this property
rowsource: set adodc2 control to this property
listfield:set name of field you want to display from adodc2 control
boundcolumn: it should be same as name of datafield property value
To create DSN follow these steps:
Start->control Panel->administrative tools->data sources->click on system dns
tab ->click on add command button ->select Microsoft access driver(*.mdb and
click on finish command button )-> specify data sourcename e.g. student2 then
Click on select command button and select the database you want to work on
e.g.
C:\Documents and Settings\COMPAQ\My Documents\student2.mdb->ok->Ok

To bring ADO control and datalist/datacombo control in toolbox follow these


steps:
Use project->components->tick mark Microsoft ADO Data Control 6.0(OleDB)
option and tick mark Microsoft data list control 6.0(OLE DB) then click on OK.

Downloaded by Manoj BE (manojporsche24@gmail.com)


lOMoARcPSD|3433744

place ADO data control, labels, textboxes and datacombo on form and set
following properties for data control
connectionstring :select ODBC data source name radio button and select dsn
created earlier
e.g. student2
recordsource: select command type adcmdtable from first combo box and select
the name of table from second combo box then click on ok
e.g test
or select command type adcmdtext from first combo box and specify sql
statement in text box such as
select * from test

set datasource property of datacombo and other text boxes to adodc1 data
control and set datafield properties.

place another ADO data control and set following properties:

connectionstring :select ODBC data source name radio button and select dsn
created earlier
e.g. student2
recordsource: select command type adcmdtable from first combo box and select
the name of table from second combo box then click on ok
e.g student
or select command type adcmdtext from first combo box and specify sql
statement in text box such as
select * from student

set rowsource property of datacombo and to adodc2 data control and set
listfield propertiy to studentname and set boundcolumn to rollno

Using Data form Wizard.


Data form wizard is useful to create data entry screen using ado code/ado data
control/ using class

Downloaded by Manoj BE (manojporsche24@gmail.com)


lOMoARcPSD|3433744

To use this wizard follow these steps:


project->add form-> select vb data form wizard>open
when asked form what profile do you want to load your setting click on next
When asked for select a database format from the list then choose Remote
ODBC then click on next.
choose dsn name from the combo box and click on next
When asked what name do you want for the form: give suitable name for form.
Choose form layout as single record and database binding as ado data control
then click on next.
Specify table name in recordsource then specify fields you want to show on
forms. You have to select fields from first list box and you have to move it on
second list box. If you like you can change order of field. If you want records
should appear sorted than you can specify the field on which sorting of records
will be done. Then click on next
specify various buttons that should be placed on form for the purpose of add,
edit, delete and update, refresh then click on next
To test the newly added form to the project we should make it startup object. To
do so use project->project properties->startup object-> select the form
Then run the project.

Creating Data Report


Data report is useful to prepare report. Data environment must be used for data
report.
Setting data environment
project->add dataenvironment

right click on connection1 and select properties. Under provider tab from the list
box select Microsoft oledb provider for odbc driver and click on next
specify data source name(dsn)
when clicked on test connection, connection succeeded message must appear if
it appears click on Ok
again right click on connection1 and select add command.

Downloaded by Manoj BE (manojporsche24@gmail.com)


lOMoARcPSD|3433744

right click on command1 and select properties


specify database object: select table from the combo
specify object name: select name of table

preparing data report


project->add data report
click on title bar of data report1 and press f4 to bring properties window
set datasource to dataenvironment1 and datamember to command1
right click on data report and select retrieve structure when asked click on yes
make sure data environment and data report both are visible
drag command1 and drop it on below detail band.( box with dotted roundings is
rptlabel control and box with solid rounding is rpttextbox)
draw a rptlabel below report header and set its caption property and font
use project-> project properties->startup object->data report1
or
place a command button on form1 and inside the click event of command button
write statement
datareport1.show

Using Data report with groups


Data report is useful to prepare report. Data environment must be used for data
report.
Setting data environment
project->add dataenvironment

right click on connection1 and select properties. Under provider tab from the list
box select Microsoft oledb provider for odbc driver and click on next
specify data source name(dsn)

Downloaded by Manoj BE (manojporsche24@gmail.com)


lOMoARcPSD|3433744

when clicked on test connection, connection succeeded message must appear if


it appears click on Ok
again right click on connection1 and select add command.

right click on command1 and select properties


specify database object: select table from the combo
specify object name: select name of table

click on grouping tab: tick mark group command object and select field on which
grouping is required from first list box and move it to second list box. Click on OK

preparing data report


project->add data report
click on title bar of data report1 and press f4 to bring properties window
set datasource to dataenvironment1 and datamember to Command1_Grouping
right click on data report and select retrieve structure when asked click on yes
make sure data environment and data report both are visible
drag command1 and drop it on below detail band.( box with dotted roundings is
rptlabel control and box with solid rounding is rpttextbox)
draw a rptlabel below report header and set its caption property and font
draw controls rptlabel, and rptfunction in group footer band and set
datamember to command1 for rptfunction control and set function type to
rptFuncRCT for rptfunction control. Set caption of rptlabel : No. of Student in
class
draw controls rptlabel, and rptfunction in report footer band and set
datamember to command1 for rptfunction control and set function type to
rptFuncRCT for rptfunction control. Set caption of rptlabel : No. of Student
use project-> project properties->startup object->data report1
or
place a command button on form1 and inside the click event of command button
write statement
datareport1.show

Downloaded by Manoj BE (manojporsche24@gmail.com)


lOMoARcPSD|3433744

Drag and drop Operation


Drag operation: when we position mouse pointer on a control and hold down
mouse button and drag a control it is known as drag operation
Drop operation: while dragging a control and when we drop the control being
dragged on other control it is known as drop operation.
Example-1

In this example we will drag a label control on to text box and text box will
acquire caption of label control in its text property.

Private Sub Label1_MouseDown(Button As Integer, Shift As Integer, X As Single,


Y As Single)
If Button = 2 Then ‘ if button pressed is right mouse button
Label1.Drag ‘start dragging of label
End If
End Sub

Private Sub Text1_DragDrop(Source As Control, X As Single, Y As Single)


If Source Is Label1 Then
Text1.Text = Label1.Caption
End If
End Sub

Using DTpicker control.


DTPicker control is useful to let the user select date.
Its useful property is value which stores the date value picked up by user.

Start new standard exe project


Project->components->tick mark before Microsoft common control 2 6.0(SP)
and click on Ok.

Downloaded by Manoj BE (manojporsche24@gmail.com)


lOMoARcPSD|3433744

Place Dtpicker control on form and a command button

Example-1

Private Sub Command1_Click()


MsgBox "Your Date of Joining is " + CStr(DTPicker1.Value)
End Sub

Using Calendar control.


Calendar control is useful to let the user select date.
Its useful property is value which stores the date value picked up by user.

Start new standard exe project


Project->components->tick mark before Microsoft Calendar control and click
on Ok.
Place calendar control on form and a command button

Example-1

Private Sub Command1_Click()


MsgBox "Your Date of Joining is " + CStr(Calendar1.Value)
End Sub

Using Print Dialog Control


1. use project->components->Microsoft common dialog control 6.0
2. place a text box, a command button
3. for textbox set multiline to true, scrollbars to both
4. for command1 set caption to print
5. place common dialog control on form
6. in command1_click write following codes
With CommonDialog1
.FromPage = 1

Downloaded by Manoj BE (manojporsche24@gmail.com)


lOMoARcPSD|3433744

.ToPage = 1
.Copies = 1
.ShowPrinter
End With

Creating mdi project


1. start new standard exe project
2. project->add mdi form
3. select form1 and set its mdichild property true
4. design menu in mdi form as follows
File
New
Windows
Cascade
Tile Horizontal
Tile Vertical

And for mdiform1 set autoshowchildren to false


Set mdiform1 as startup object using project->project properties-> startup
object to mdiform1

For windows menu item check windowlist checkbox so as to see list of


documents open. In code editor window of mdiform1 type following codes.

Dim counter As Integer

Private Sub mnucascade_Click()


MDIForm1.Arrange vbCascade
End Sub

Private Sub mnunew_Click()


Dim f As New Form1

Downloaded by Manoj BE (manojporsche24@gmail.com)


lOMoARcPSD|3433744

counter = counter + 1
f.Caption = "New Dcoument :" + CStr(counter)
f.Show
End Sub

Write short notes on on error, resume statements in VB.


Vb provides many tools for debugging project
on error goto label/line no: when you execute an on error goto label/line
no statement in your code execution is transferred to the code starting at label if
a trappable error has occurred. The code following that label is your error
handler.
on error goto 0: if you want to turn off error trapping at some point in your
code, you can execute the statement on error goto 0 just before that piece of
code . then again you can give on error goto label statement for error trapping
after that piece of code.
on error resume next: on error resume next statement provides an easy
way to disregard errors, if you want to do so. Once you execute this statement,
execution continues with the next line of code if the current line generates an
error, and the error is disregarded.
resume:  when you are writing code for an error handler, you can return
control to the main body of the procedure using the resume statement. Program
execution starts again with the line that caused the error, and this can be very
valuable if you are able to fix the error in the error handler.
resume label: when your are writing code for an error handler, you can
return control to a particular line in the main body of the procedure using the
resume label statement. To a label a line, you just place the label’s text directly
into the code, followed by a colon.
resume next: this statement resumes program execution in the
line after the one that caused the error.

Types of error
Error are of different types
logical error: logical error is an error that is difficult to find out we use debugging
tools to find out logical error. In logical error for a set of supposed input desired
output is not achieved.
Compile time error: this type of error is normally generated due to incorrect
syntax used in writing statement. Auto syntax check feature of vb checks syntax

Downloaded by Manoj BE (manojporsche24@gmail.com)


lOMoARcPSD|3433744

error while writing source code.Compile time error is generated during


compilation of program( in vb while making executable file)
Run time error: in this type of error program runs successfully but for given set of
input result obtained is right and for another set of values the result obtained is
wrong.
Error calling chain
if x is a procedure and it has error handling routine, x calls procedure y and y
doesn’t have error handling routine and a statement in y generates error then x’s
error handler routine will cope with error occurred in y
if x is a procedure and it has error handling routine, x calls procedure y and y has
error handling routine and a statement in y generates error then y’s error
handler routine will cope with error occurred in y
error in error handling routine
suppose you have written error handling routine to cope with erroneous
statement. You have written some statements inside error handling routine and
the statement written inside error handling routine itself contains some
erroneous statement then what will happen?
error handling styles.
There are two different error handling styles:
1 . structured ( uses try..catch..finally… throw and throws) used in vb.net, java
and c++.
2. unstructured ( uses on error goto label and resume) used in vb.

What are err object and error function ?


err: err is an object if we use err.number then it gives error no. that occurred in
statement, if we use err.description it gives short description of the error
occurred, if we use err.raise we can raise an error intentionally.
error: it is a function if we give error no. as argument to it, it gives us error
description.
e.g. msgbox error(5) it will give invalid procedure call or argument
msgbox error(11) it will give division by zero
Write short notes on debugging tools in vb.
Visual basic offers a powerful suite of debugging options-notable the ability to
single – step through your code as it is executing. The standard way to debug is
to place a breakpoint at a particular line in your code, and when execution
reaches that line, it will halt and visual basic will enter the debug state, give you
access to your code and variables. You can examine the contents of those
variables and work through your code line by line, watching program execution

Downloaded by Manoj BE (manojporsche24@gmail.com)


lOMoARcPSD|3433744

behind the scenes.


To move through your program step-by-step you can select these stepping
options in the debug menu:
step into-single step though the code, entering called procedures if encountered.
step over- single-step through the code, stepping over procedure calls.
step out- step out of the current procedure.
Setting debugging breakpoints
Breakpoints are the foundation of vb debugging. When you set breakpoints in a
program and run that program, program execution continues until one of the
breakpoints is encountered and program execution stops, making vb enter the
debug state. You place a breakpoint in code by moving the text insertion caret to
that line and either selecting toggle breakpoint in the debug menu or pressing f9.
Examining variable and expression: just select the expression and press
shift+f9 to evaluate variable and expression.
Adding debug watch windows: you can add a watch window to your
debugging session and display the values of selected variables or expressions in
that window continuously as you execute your program line by line.
Immediate window: when debugging, you can use the immediate window to
examine expressions or variables immediately, just by typing them in.

On error goto label and resume statement demo

Private Sub Command1_Click()


On Error GoTo myroutine
'myroutine is a label where control will transfer if error occurs
'you could have used any label in place of myroutine
Dim m!, n!, p!
m = Text1.Text
n = Text2.Text
p=m/n
Text3.Text = p
Exit Sub

myroutine:

Downloaded by Manoj BE (manojporsche24@gmail.com)


lOMoARcPSD|3433744

If n = 0 Then
n=1
Resume ' execute the same statement caused error
End If
End Sub

On error goto label and resume label

Private Sub Command1_Click()


On Error GoTo myroutine
'myroutine is a label where control will transfer if error occurs
'you could have used any label in place of myroutine
Dim m!, n!, p!
m = Text1.Text
n = Text2.Text
p=m/n
pp: Text3.Text = p
Exit Sub
myroutine:
If n = 0 Then
n=1
Resume pp 'resume with label
End If
End Sub

On error goto label and resume next

Private Sub Command1_Click()


On Error GoTo myroutine
'myroutine is a label where control will transfer if error occurs
'you could have used any label in place of myroutine
Dim m!, n!, p!

Downloaded by Manoj BE (manojporsche24@gmail.com)


lOMoARcPSD|3433744

m = Text1.Text
n = Text2.Text
p=m/n
Text3.Text = p
Exit Sub
myroutine:
If n = 0 Then
n=1
Resume next 'resume the statement appearing next to the statement caused
errorl
End If
End Sub

Using on error resume next and on error goto 0 (inline error handling)

Private Sub Command1_Click()


Dim a(0 To 2) As Integer
Dim m!, n!, p!
m = Text1.Text
n = Text2.Text
On Error Resume Next
p=m/n
Text3.Text = p
On Error GoTo 0 'disable previouse error handling routine if any
a(5) = 20 'now this error will terminate the program
MsgBox "value of element having index 5 is =" + CStr(a(5))
End Sub
Using err object (inline error handling)

Private Sub Command1_Click()


Dim a(0 To 2) As Integer
Dim m!, n!, p!
m = Text1.Text

Downloaded by Manoj BE (manojporsche24@gmail.com)


lOMoARcPSD|3433744

n = Text2.Text
On Error Resume Next
p=m/n
If Err Then ‘err object will be true if previous statement caused error
Text3.Text = m ‘ you can use err.number to get error no. and to get error
description use
‘err.description
Else
Text3.Text = p
End If
End Sub
Differentiate binary and random file

Binary Random

It is to read or write data such as Random files are used to read write
data of ole controls, image files, text data in terms of fixed record
data field in a table of data type length. less commonly used to read/
blob(binary large object) etc. less write binary data in terms of fixed
commonly used to read text data. length record.

It does not allow random access It allows random access of data.

Binary can make use of input Random can not make use of input
function function.

Type..end type statement is not Type..end type statement is used to


useful. created user defined data type
which helps to create fixed record
length.

Differentiate sequential and random access file.

Sequential Random

Downloaded by Manoj BE (manojporsche24@gmail.com)


lOMoARcPSD|3433744

Sequential does not use record of Random uses record of fixed length.
fixed length.

Sequential is useful to read text data Random can be used to read text
in sequence. and binary data in terms of fixed
record length.

Sequential allows slow access of Random allows fast access of record


record randomly.

Sequential file can use following It can use get and put statement
statements which random file can which can not be used by sequential
not use: input, input#,line file.
input ,print #,write#

Reading and writing in sequential file

Private Sub Command1_Click()


Dim p$, q$, r$
p = Text1.Text
q = Text2.Text
r = Text3.Text

' if you open file in output mode if data exists in file, file's data is lost
' if you open file in append mode if data exists in file you can write new data at
the end of
' file. if file doesn't exist then new file is created
Open "data.txt" For Append As #1
Write #1, p
Write #1, q
Write #1, r
Close #1

Downloaded by Manoj BE (manojporsche24@gmail.com)


lOMoARcPSD|3433744

End Sub

Private Sub Command2_Click()


On Error GoTo errhand
Open "data.txt" For Input As #1
pp: Input #1, p
Input #1, q
Input #1, r
Text4.Text = p
Text5.Text = q
Text6.Text = r
If vbOK = MsgBox("read next record", vbOKCancel) Then GoTo pp
Close #1
Exit Sub
errhand:
MsgBox "No More record in file"
Close #1
End Sub

Reading and writing file in random mode

Downloaded by Manoj BE (manojporsche24@gmail.com)


lOMoARcPSD|3433744

Private Type student


sname As String * 20 'only 20 characters are allowed
srollno As Integer 'if fewer characters are given then space is padded to make
its
sclass As String * 20 ' length 20
'it is fixed length string
End Type
Dim s As student
Dim recordno As Integer
Private Sub Command1_Click()

s.sname = Text1.Text

Downloaded by Manoj BE (manojporsche24@gmail.com)


lOMoARcPSD|3433744

s.srollno = Text2.Text
s.sclass = Text3.Text
recordno = InputBox("enter record no. where you want to write record")
'size of record will be fetched using len(s)
Open "data.rnd" For Random As #1 Len = Len(s)
Put #1, recordno, s
Close #1
End Sub

Private Sub Command2_Click()


On Error GoTo errhand
Open "data.rnd" For Random As #1 Len = Len(s)
pp: recordno = InputBox("enter record no. from where you want to read
record")
Get #1, recordno, s
Text4.Text = s.sname
Text5.Text = s.srollno
Text6.Text = s.sclass
If vbOK = MsgBox("read next record", vbOKCancel) Then GoTo pp
Close #1
Exit Sub
errhand:
msgbox err.description
Close #1
End Sub

The extended text editor


The extended text editor stores formatting of text along with actual text inside a
file and when file is read back not only text appears but also formatting is applied
on text. For example if we have written some text in a text box and we have
made it bold and italic and save it in the file then when we read back the file we
will get text with bold and italic formatted.

Difference between databound and data control.

Downloaded by Manoj BE (manojporsche24@gmail.com)


lOMoARcPSD|3433744

Data bound control receives data from data control and have data source, data
member, data field properties. Data control has databasename, record source
and other properties. Data control connects with database and table and
supplies data to databound control.
Using validate event
Normally every control has validate property which is by default
true therefore control can generate validate event. Validation
event has an argument if this argument is assigned value true
then control can loose its focus if the argument is assigned value
false then focus remains in the  control.

Downloaded by Manoj BE (manojporsche24@gmail.com)

Вам также может понравиться