0% found this document useful (0 votes)
4 views

CONTROL ARRAY

The document provides an overview of control arrays, menus, and database management in Visual Basic, detailing how to create and manipulate control arrays, set up menus, and interact with databases using data controls. It explains the structure of databases, the role of database management systems (DBMS), and the different methods of accessing databases such as DAO, RDO, and ADO. Additionally, it outlines the steps to link a Visual Basic application to a Microsoft Access database and the properties of data controls and data-bound controls.

Uploaded by

gladys temwo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

CONTROL ARRAY

The document provides an overview of control arrays, menus, and database management in Visual Basic, detailing how to create and manipulate control arrays, set up menus, and interact with databases using data controls. It explains the structure of databases, the role of database management systems (DBMS), and the different methods of accessing databases such as DAO, RDO, and ADO. Additionally, it outlines the steps to link a Visual Basic application to a Microsoft Access database and the properties of data controls and data-bound controls.

Uploaded by

gladys temwo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 100

CONTROL ARRAY:

• These are array made by grouping a set of


controls together. The controls must be of the
same type like all TextBoxes or all
CommandButtons.
• A control array is a group of controls that share
the same name type and the same event
procedures. Adding controls with control arrays
uses fewer resources than adding multiple
control of same type at design time.
Creating control arrays
• Place some same type of controls say
CommandButtons on the form. Make their
name properties same and then a warning
(see picture below) dialog box will come
asking whether you want to create a control
array, click Yes.
• After placing a control on the form, copy that
and paste on the form. It will create control
array for you.
• Set the Index property of each control or you
may not change as it is automatically set.
• Now its done. You are ready to use the control
array in your code.
Manipulating control array
• Syntax to refer to a member of the control
array : Control_Name(Index).Propert
• Example:
• Command1(1).BackColor = vbGreen
Control array is useful when you want to clear a set of TextBox
fields. Create a control array of 5 TextBox controls and write
the following code in the Click event procedure of a
CommandButton control
• Private Sub Command2_Click()
• Dim i As Integer
• For i = 0 To 4 'Or, For i=Text1.LBound To
Text1.UBound
• Text1(i).Text = ""
• Next i
• End Sub
example2
• Private Sub Command2_Click()
• Command1(0).Caption = "first"
• Command1(1).Caption = "Second"
• Command1(2).Caption = "Third"
• End Sub
Program to get sum and difference
• Private Sub Command1_Click(Index As Integer)
• Dim x As Integer, y As Integer, sum As Integer,
subtraction As Integer
• x=3
• y=4
• sum = x + y
• subtraction = x - y
• Command1(Index).Caption = "vbRed"
• Print sum
• Print subtraction
• End Sub
MENU
• Windows applications provide groups of
related commands in Menus. These
commands depend on the application, but
some-such as Open and Save are frequently
found in applications.
• Menu enable the users to quickly select
commands .
• Basically, each menu item has a Caption
property (possibly with an embedded
• & character to create an access key) and a
Name. Each item also exposes three
• Boolean properties, Enabled, Visible, and
Checked, which you can set both at
• design time and at run time.
• You enter the item's Caption and Name, set other
• properties (or accept the default values for those
properties), and press Enter to move to the next
item.
• When you want to create a submenu, you press the
• Right Arrow button (or the Alt+R hot key). When
you want to return to work on top-level menus—
those items that appear in the menu bar when the
application runs—you click the Left Arrow button
(or press Alt+L).
• You can create up to five levels of submenus
(six including the menu bar),
• which are too many even for the most patient
user.
Creating Menus
• Open a new Project and save the form as
menu.frm and save the project as menu.vbp.
Choose Tools ››› Menu Editor and type the
menu items as shown below.
• Caption Name
• File mnuFile
• Open mnuOpen
• Save mnuSave
• Exit mnuExit
• Edit mnuEdit
• Copy mnuCopy
• Cut mnuCut
• Paste mnuPaste
database
• A database is a collection of information. This
information is stored in a very structured
manner.
• The smallest unit in a database is called a field
(data item). •
• A record is a collection of fields.
• A table (file) is a collection of records.
• A database is a collection of one or more
tables.
database management system
(DBMS).
• each database requires some way for a user to
interact with the information within. Such
interaction is performed by a database
management system (DBMS).
The tasks of a DBMS are really quite
simple
• 1.View the data
• 2. Find some data of interest
• 3. Modify the data
• 4. Add some data
• 5. Delete some data
Examples of DBMS
• Programs like Access (a Microsoft product)
and Oracle
• A Visual Basic application cannot directly
interact with a database.
• There are two intermediate components
between the application and the database:
the data control and the database engine:
data control
• The data control is a Visual Basic object that
connects the application to the database via
the database engine.

• It is the conduit between the application and


the engine, passing information back and
forth between the two.
Data control cont’
• The Data control is a link between the
information in your database and the Visual
Basic control that you use to display the
information. E.g a textbox
DATA BOUND CONTROL
• A data-bound control, such as a list box, a grid
or a text box, is a control that is hooked up to
a data source.
Data control Data-bound

Using data control is a two-step process. You create the controls, such as labels
First you place a data control on a form and text boxes, to display the actual data.
and set the properties to link it to a Each control is a bound to particular field
database file and table in the table. In this example the label is
called a data bound control and
automatically displays the contents of
bound field when the project runs.

Data control generally links one form with If you want to have data-bound controls on
one table. second form, you must place a data
control on that form.

Prefix of data control is “dat” For data-bound control prefix depends


upon the control which you are using.
database engine
• The database engine is the heart of a Visual
Basic database management system.
• It is the actual software that does the
management. Having this engine saves
programmers a lot of work. The database
engine native to Visual Basic is known as the
Jet engine.
database accessing methods are as
follows;
• Jet Engine - Accessing Microsoft Access and
Visual Basic databases.
• 2. ODBC (Open Database Connectivity) - Allow
access to the client server databases on a
network.
• 3. ISAM (Index Sequential Access Method) -
Used to access flat databases such as dBase,
FoxPro, ParaDox.
Visual Data Manager
• The Visual Data Manager is a Visual Basic
Add-In that allows the creation and
management of databases.
Functions of visual data manager

• Create a new database


• Open existing databases
• Add data tables to a database
• Link to information contained in other databases
• Add fields and indexes to a database
• Set relationships between data tables
• Enter and find data in data tables
• Enter and save SQL statements
• Compact and repair databases
• Encrypt and decrypt databases
Steps to link Student Detail Application
to Microsoft Access database:
• 1. In menu bar go to Add-Ins → Visual Data Manager Dialog box called
Visual data will open.

2. In that select File → New → Microsoft access → Version 7.0MDB
[Microsoft Data Base].

3. Give the file name (Database Name) Eg: STUDENT and then click Save.

4. Right click on Database Window & Select New Table.

5. Table Structure Dialog box will open, type the Table Name which you
want to create Eg: STUDENT, & click on Add Field give the field Name as
NAME & Click OK.
• 6.Give another field name as REG No select
the type as Integer &click OK.
7. Give another field name as Address, click
OK then Close.

8. Click on Build the Table.

9. Right click on the STUDENT option which is
available in the database window, Select
OPEN.
• 10.Dynaset: STUDENT dialog box will open click
Add & Give the inputs & click UPDATE, repeat
this for 2 or 3 inputs. & close the Database
• Window.
• 11.Open the design window Select the Data1
Control and change the properties
DatabaseName Select the data base which is
saved in My Documents Eg: STUDENT.mdb &
Click OPEN.
• 12.In Properties select RecordSource & Select
the Table Name Eg: STUDENT.
• Select the Text1 control in the design window
and change the properties of DataSource as
Data1 & select the DataField & Select the
Attribute Name.
• 14.Repeat the same process for Text2 & Text3.
Data Access
• Data access is a feature of Visual Basic that allows
you to access and manipulate any database from
Visual Basic. The database may be either MS-
Access database or FoxPro database or it may
also be any of the relational databases such as
Oracle.
• Visual Basic provides three data access interface
1. DAO(Data Access Object)
2. RDO(Remote Data Object)
3. ADO(Active X Data Object)
Functions of Data Access Control
• 1. Connect to a database.
• 2. Open a specified database table.
• 3. Create a virtual table based on a database query.
• 4. Pass database fields to other Visual Basic tools,
for display or editing. Such tools are bound tools
(controls), or data aware.
• 5. Add new records or update a database.
• 6. Trap any errors that may occur while accessing
data.
• 7. Close the database.
DATA CONTROL PROPERTIES
• Align Determines where data control is displayed.

• Caption Phrase displayed on the data control.

• ConnectionString Contains the information used


to establish a connection to a database. E.g.
Provider = Microsoft.Jet.OLEDB.4.0;Data
Source=C:\Program Files (x86)\Microsoft Visual
Studio\VB98\BIBLIO.MDB;Persist Security
Info=False
• LockType Indicates the type of locks placed on
records during editing (default setting makes
databases read-only).

• Recordset A set of records defined by a data


control‘s ConnectionString and RecordSource
properties. Run-time only. RecordSource
Determines the table (or virtual table) the data
control is attached to.
Parts of a data control
Data Bound Tools
• Most of the Visual Basic tools we‘ve studied can be used
as bound, or data-aware, tools (or controls).
• Label - Can be used to provide display-only
access to a specified text data field.
• Text Box - Can be used to provide read/write
access to a specified text data field. Probably,
the most widely used data bound tool.
• Check Box - Used to provide read/write
access to a Boolean field.
bound controls
• Combo Box - Can be used to provide read/write
access to a text data field.
• List Box - Can be used to provide read/write
access to a text data field.
• Picture Box - Used to display a graphical image
from a bitmap, icon, or metafile on your form.
Provides read/write access to a image/binary
data field.
Bound Tool Properties:
• DataChanged - Indicates whether a value
displayed in a bound control has changed.

• DataField - Specifies the name of a field in the


table pointed to by the respective data control.

• DataSource - Specifies which data control the


control is bound to.
ways of access database.

• Data Access Objects (DAO)-used to access only local


database which is a disadvantage
• This is an object model that has a collection of
objects using which you can access a database. This
model gives complete control on the database. This
model uses Jet Engine, which is the native database
engine used by Visual Basic and MS-Access. This was
the first model to be used in Visual Basic. Though it
is possible to access any database using this, it is
particularly suitable for MS-Access database and not
suitable for ODBC data sources such as Oracle and
MS-SQL Server. So, Microsoft later introduced RDO.
Remote Data Objects (RDO)

• These objects are only used to access ODBC data


sources such as Oracle.
• ODBC (Open Database Connectivity)
• These objects access databases that are on remote
machine (database server). This object model has
less number of objects compared with DAO and
more suitable for accessing remote databases.
ActiveX Data Objects (ADO)

• The ADO Recordset object is used to hold a set of records from a


database table. A Recordset object consist of records and columns (fields).
In ADO, this object is the most important and the one used most often to
manipulate data from a database.

• This object model has very few objects and it is based on OLE DB interface.
OLE DB interface is a new interface (replacing ODBC and others), through
which you can access data of all formats in the same manner.

• ADO uses OLE DB providers to access the data. That means each database
is accessed through OLE DB provider. And ADO provides the programming
framework to access OLE DB. ADO is also much easier to deal with.
The data control can be used to
perform the following tasks:
• Connect to a database.
• 2. Open a specified database table.
• 3. Create a virtual table based on a database query.
• 4. Pass database fields to other Visual Basic tools, for
display or editing. Such tools are bound tools
(controls), or data aware.
• 5. Add new records or update a database.
• 6. Trap any errors that may occur while accessing data.
• 7. Close the database.
Data Control Properties:

• Align Determines where data control is displayed.

• Caption Phrase displayed on the data control.

• ConnectionString Contains the information used to establish a


connection to a database.

• LockType Indicates the type of locks placed on records during


editing (default setting makes databases read-only).

• Recordset A set of records defined by a data control’s


ConnectionString and RecordSource properties. Run-
time only.

• RecordSource Determines the table (or virtual table) the data


control is attached to.
DataSource
• The DataSource is the name of the data
control on the form (it should already be
configured), and the
DataField
• DataField is the name of the particular field in
the database that should be displayed in the
control (this field will be in the table that was
chosen for the RecordSource of the data
control).
DATABASE ACCESS WITH THE DATA CONTROL

• STEPS:
• 1. Open a new Visual Basic project.

• 2. Put a data control (an intrinsic control,
located in the VB toolbox) on the form and set
the properties as follows:
PROPERTIES OF DATA CONTROL

Property Value

(Name) datAuthors

Caption Use the arrows to view the data

Connect Access (default)

DatabaseName ..\biblio.mdb

DefaultType UseJet (default)

RecordSource Authors (choose from list)


POINT TO NOTE
• When you use the Data Control in a project,
the properties that must be set are
DatabaseName and RecordSource, in that
order. DatabaseName is the name of the
database you want to use, and the
RecordSource is the name of the table in
that database that you want to use.

BOUND CONTROLS
• On your form, create a text box for each
field in the Authors table, with labels. (If
you were to open the database in Access,
you would see that the three fields of the
Authors table are Au_ID, Author, and Year
Born.) Set the properties of the three
textboxes as follows:
EXAMPLE

Name DataSource DataField

txtAuthID datAuthors Au_ID

txtAuthor datAuthors Author

txtYearBorn datAuthors Year Born


• When you want a control (such as a text box)
to display data from a database, the
properties that must be set are DataSource
and Datafield. The DataSource is the name
of the data control on the form (it should
already be configured), and the DataField is
the name of the particular field in the
database that should be displayed in the
control (this field will be in the table that was
chosen for the RecordSource of the data
control).
• 4. Save and run the project. Use the
arrows on the data control to scroll through
the data.

METHODS OF THE RECORDSET
OBJECT
1. MoveFirst,
2. MovePrevious,
3. MoveNext,
4. MoveLast
USING THE BOFACTION AND EOFACTION PROPERTIES OF THE DATA CONTROL

• EOF (End Of File) is a Boolean property of


the recordset object that becomes true when
an attempt is made to move forward past the
last record in a recordset.

• BOF (Beginning Of File) is a Boolean
property of the recordset object that becomes
true when an attempt is made to move
backward past the first record in a recordset.
• Click once on the data control and make
sure that the following properties are set:

• BOFAction = 0 – Move First
EOFAction = 0 – Move Last
code in the cmdMoveNext_Click() event:


• datAuthors.Recordset.MoveNext
If datAuthors.Recordset.EOF =
True Then
datAuthors.Recordset.MoveLast
• End If
AddNew method of the recordset
object
• causes all the bound controls to be
cleared so that the user can enter data
ADDNEW CODE
• datAuthors.Recordset.AddNew
cmdSaveRecord.Enabled = True
• cmdMoveFirst.Enabled = False
cmdMoveLast.Enabled = False
cmdMovePrevious.Enabled = False
cmdMoveNext.Enabled = False
• cmdDeleteRecord.Enabled = False
cmdNewRecord.Enabled = False
SAVE BUTTON
• Private Sub Command2_Click()
On Error GoTo err1
Data1.Recordset.Update
MsgBox ("One Record is successfully Saved")
err1:
MsgBox ("Record Updated Successfully")
End Sub
Clear command
• Private Sub Command4_Click()
• Text1.Text = ""
• Text2.Text = “”
• End sub
Delete method
• On Error GoTo Delete_Error

• If MsgBox("Are you sure you want to delete this record?", _
• vbQuestion + vbYesNo + vbDefaultButton2, _
• "Confirm") = vbNo Then
• Exit Sub
• End If

• 'delete the current record
• datAuthors.Recordset.Delete

• 'move to a valid record
• cmdMoveNext_Click

• Exit Sub

• Delete_Error:
• ' This error will occur if you attempt to delete an author that is related to
• ' another table in the biblio.mdb database ...
• MsgBox "This record cannot be deleted. Error code = " _
• & Err.Number & vbCrLf & Err.Description, _
• vbCritical, "Cannot Delete"
DATABASE CONNECTION USING ADO
• ADO control. ADO stands for ActiveX data
objects. As ADO is ActiveX-based, it could
work in different platforms (different
computer systems) and different programming
languages.

• ADO is a programming interface to access data


in a database
Ways of Connecting to
Databases Using ADO

• ADO Data Control


• Connecting in code using ADO Connection
• Object
• Data Environment
ADO LockType Property
• The LockType property sets or returns a
LockTypeEnum value that specifies the type of
locking when editing a record in a Recordset.
Default is adLockReadOnly.
Lock types
• adLockUnspecified
• Unspecified type of lock. Clones inherits lock type
from the original Recordset
• adLockReadOnly
• Read-only records
• adLockPessimistic
• Pessimistic locking, record by record. The
provider lock records immediately after editing
• adLockOptimistic
• Optimistic locking, record by record. The
provider lock records only when calling update
• adLockBatchOptimistic
• Optimistic batch updates. Required for batch
update mode
ADO Connection Object

• The ADO Connection object is used to create


an open connection to a data source. Through
this connection, you can access and
manipulate a database.
Components of ADO objects
• Connection:The connection object is ADO's
connection to a data store via OLE DB. The
connection object stores information about
the session and provides methods of
connecting to the data store
Components of ADO objects
• Command
• After the connection object establishes a session
to the data source, instructions are sent to the
data provider via the command object.
• The command object can send SQL queries
directly to the provider through the use of the
CommandText property, send a parameterised
query or stored procedure through the use of a
Parameter object or Parameters collection or run
a query and return the results to a dataset object
via the Execute method.
Components of ADO objects
• Recordset
• A recordset is a group of records, and can
either come from a base table or as the result
of a query to the table.

• The RecordSet object contains a Fields


collection and a Properties collection. The
Fields collection is a set of Field objects, which
are the corresponding columns in the table.
Components of ADO objects
• Record
• This object represents one record in the
database and contains a fields collection. A
RecordSet consists of a collection of Record
objects..
Components of ADO objects
• parameter

• A parameter is a means of altering the


behaviour of a common piece of functionality,
for instance a stored procedure might have
different parameters passed to it depending
on what needs to be done; these are called
parameterised commands.
Components of ADO objects
• field
• Each Record object contains many fields, and
a RecordSet object has a corresponding Field
object also. The RecordSet object's Field
object corresponds to a column in the
database table that it references.
Components of ADO objects

• Error
• When an OLE DB provider error occurs during
the use of ADO, an Error object will be created
in the Errors collection. Other errors do not go
into an Error object, however. For instance,
any errors that occur when manipulating data
in a RecordSet or Field object are stored in a
Status property..
ADDING MICROSOFT ADO DATA CONTROL 6.0 (OLEDB)
COMPONENT

• 1. Click project on the menu. From the


dropdown click Components
2. From the pop up window select
“Microsoft ADO Data Control 6.0 (OLEDB)”.
3. Click Apply then OK
• 5. Click Adodc Tool and add it to the form as
Shown Below
Configuring ADODC to connect to
Access Database
• Right Click on Adodc1 and select ADODC
Properties as shown below.
2. From the Property Pages “Using
connection String” Click on Build
From the Data Link Properties Window
select “Microsoft Jet 4.0 OLE DB
Provider”
Click the Next Button connect to the
database as shown below.
• Browse to select the database and Test the
connection to confirm that it succeeds.
• 6. From the “Microsoft Data Link” Click “OK”
The Connection string is now created.
Apply and Click OK
ADO Command Object

• The ADO Command object is used to execute


a single query against a database. The query
can perform actions like creating, adding,
retrieving, deleting or updating records.
Properties
of command object
Property Description

Sets or returns a definition for a


connection if the connection is closed, or
ActiveConnection
the current Connection object if the
connection is open

CommandText Sets or returns a provider command

Sets or returns the number of seconds to


CommandTimeout wait while attempting to execute a
command
property
Description

Sets or returns the type of a


CommandType
Command object

Sets or returns the name of a


Name
Command object

Sets or returns a Boolean value that,


if set to True, indicates that the
Prepared command should save a prepared
version of the query before the first
execution

Returns a value that describes if the


Command object is open, closed,
State
connecting, executing or retrieving
ADO Recordset Object

• The ADO Recordset object is used to hold a set


of records from a database table. A Recordset
object consist of records and columns (fields).

• In ADO, this object is the most important and


the one used most often to manipulate data
from a database.
Recordset objects can support two
types of updating:

• Immediate updating - all changes are


written immediately to the database once you
call the Update method.
• Batch updating - the provider will cache
multiple changes and then send them to the
database with the UpdateBatch method.
ADO cursor types
• Dynamic cursor - Allows you to see additions,
changes, and deletions by other users.
• Keyset cursor - Like a dynamic cursor, except
that you cannot see additions by other users,
and it prevents access to records that other
users have deleted. Data changes by other
users will still be visible.
ADO cursor types
• Static cursor - Provides a static copy of a
recordset for you to use to find data or generate
reports. Additions, changes, or deletions by other
users will not be visible. This is the only type of
cursor allowed when you open a client-side
Recordset object.
• Forward-only cursor - Allows you to only scroll
forward through the Recordset. Additions,
changes, or deletions by other users will not be
visible.

You might also like