Use of All Basic Controls@
Use of All Basic Controls@
Use of All Basic Controls@
VB building Components
(1) Forms
(2) Controls
(3) Properties
Forms and controls are the components that users see and interact with,
so these objects are collecting known as program’s visual component.
And the program code that the program creates is known as program’s
code component.
(1) FORMS
A form is a container that holds all the other controls like text boxes,
pictures etc that make up part of a program’s user interface.
Program can have single or multiple forms. It is possible to create VB
program that contains no forms at all.
The design time form contains a grid of dots that allows to line up
controls easily on the form. Behavior of the design grid can be controlled
through the options dialog box(Tool menu, options). Using options dialog box
size of the grid can be changed or if can be turned off completely. Automatic
alignment of controls to grid can also be turn on / off from options dialog box.
Functions of forms
(1) Forms represent program’s user interface.
(2) Forms are the containers for the controls that users works with like text
box, buttons etc.
(3) Program code related to all the objects on a particular form is stored as a
part of form its if.
CONTROLS
Visual Basic controls are objects designed to perform specific tasks.
Controls have associated properties, events and methods.
Control is just like a mini program that performs certain tasks for you.
Controls are prepackaged objects that perform specific tasks. Ex. If you assign
20 size of the text of text box the it will display character of size 20 only for
that a text box contains inter code that allows to perform the task.
Toolbox for common controls is displays in left pane of the screen.
PROPERTIES
A property is an adjective that describes one specific thing about an
object. By changing value of one or more property, object’s appearance can be
customized.
Form appears as a rectangular window on screen. This window’s
appearance can be defined by form properties, like position of form on screen,
size of form by width and height properties, content of title bar by caption
property. Using some properties it can also be specified that which control
buttons will appear in title bar.
When any form is saved as a part of a project, VB creates a text file with
an FRM extension. This file stores information about form, its properties
objects of the form, objects properties and program code that is generated for
that form.
Common Properties
- Name
- Index
- Left
- Top
- Height
- Width
- Enabled
- Visible
CONTROLS
(1) Label Control
A label control is used to display text to the user. This control is
typically used to identify input areas directly to right or below the label.
Common properties of label : font, fore color, height
(0) Appearance : O-flat / 1-3D
(1) Alignment : To align text left, right / center within the label.
(2) Auto size : This property will automatically size (True/ false) the
control to the height and width of the text that is displayed in it. (0
None, 1 fixed size)
(3) Border style : displays border around the label
(4) Caption : display text inside the label.
(5) Name : To identify the name of the control.
(6) Visible : Indicates whether the control is visible True/False.
(7) Word Wrap : It set to true, this property or not allows True/False the
caption to wrap to another line.
Frame Control:
The frame control allows to insert a group of controls into a box and add
a caption to describe the purpose of these controls. It’s a contain into a frame,
those controls can be identified as part of a group.
[ A container control is any control that acts as a parent to all the
controls within it].
Common Properties:
(1) Caption : Set this property to the value you want to display on the top-left
side of the frame.
(2) Enabled: If it is set to false so all the controls in the frame are disabled.
(3) Visible : If it is false then all the controls in the frame will become
invisible.
(4) Border style - 0 - None – No border
1 – Fixed single
If border style is set to none then no border is displayed and the caption
is also not displayed because it is also a part of the border.
If you change the control on the frame that are already on the form then
those controls are not contained by the frame.
Controls cannot be moved in or out of the frame by change & chop
method.
To move the control from other part of the form into the frame, cut that
control and paste it in the frame.
A list box control is used to provide a list of items to user form which user can
make choice. User can make selection only from the available items. New
items can not be added by the user.
Properties:
List property is used to add the items to the combo box at design time. It’s an
array of items added to the combo box control.
Name property is used to assign meaningful name to the combo box control.
Preface the name with ‘cbo’.
Sorted property: Set it to true to display list items in a sorted order. If it is
false then items will be displayed in an order in which they are added to the
combo box.
IntergalHeight Property: If it is true, the combo box calculates the number of
rows it can display and adjusts the height of combo box so it can display only
full rows of data without cutting a row in half. If it is set to false, the combo
box can be set to any size of your choice.
Style Property:
0 – DropDown Combo:
With this style, user can either type text into the text portion of
the combo box or select a value from the drop down list.
1 – Simple Combo:
This style will not give list of items as a drop down list but it
provides it in form of list box only. This will require more space
on the form.
2 – DropDown List:
This style allows to select item only from the available list. It
does not allow to type any text in the text portion.
Timer Control :
The timer control works like a stopwatch or an alarm clock. It executes
code written in it’s timer event, when the specified interval is complete. It
counts down repeatedly as long as the enabled property is set to true.
Properties:
(1) Enabled: True then timer control enabled of the code in the timer event is
executed at the end of the time specified in interval property.
(2) Interval: Set this property to any value between zero & 65,635. If it is set
to zero then timer control is disabled. Time can be specified in
milliseconds.
Ex:-
Private Sub Timer1_timer( )
Picture. Left = Picture1.left + 100
If picture. left > Form1.width
Then picture. left = 0
End sub.
In VB, two control are available to display picture on the form. Image
control & Picture box control.
Image Control:
This control allows to display picture of the form, that can be placed
anywhere on the form. To display image within image control, picture property
is used.
Another important property of image control stretch.
If stretch-false the image control is automatically resized to fit the
picture within it . If it is set to true, the picture is automatically resized so that
the entire picture fits with in image control’s boundaries.
Picture Control:
It can be used as a container for other controls. Controls within a group
can be treated as a group. It will more or resize with from.
The main difference between picture box & image control is that the
picture doesn’t allow resizing of the picture. It shoes only as much of a picture
as if can fit in its current bound.
Authorize True – Resize the picture box so it can fir the entire picture with
if.
Align More /Align left / Align Right / Align Top / Align Bottom. To make
picture control align or not align to the sides of from.
Vb Exclamation - Vb information -
Project X
Hello
OK
Last Name X
OK
Update Table X
OK
Massage (“Are you sure?” Vb yes no + Vb Question, “Quit”) + Vb
Default button2
Quit X
Yes No
User Name
Pass word
Continue Exit
Title X
Prompt OK
Cancel
added in the common tool box. Click this control & draw if on
the form. It will appear as an icon on the form but it will not be
displayed when you will run the project. Using this icon different
different dialog boxes can be added. For that go to it’s property
page by right clicking on icon & selecting properties or from
property window go to custom property.
OK CANCEL APPLY
Now let’s consider one example in which we will add dialog
box to open a file.
Open file
CommandOpen
TOOLBAR
Toolbars provide an easy way to access the must commonly
used functions of the project.
Toolbar control allows to create six different types of buttons ;
1. Push buttons
2. Check buttons
3. Button group
4. Place holder buttons
5. Drop down buttons
6. Separator buttons
To chew a toolbar on the form, first add the tool that allows to
toolbar to the toolbox,
Project components Microsoft windows common controls
6.0
It will add 9 different buttons (tools) to the toolbar select tool
for toolbar & draw it on form. By default, it will be aligned to the top
of the form but alignment can be changed by changing align
property.
1 - VbAlignTop – Default
2 – VbAlignBottom
3 - VbAlignleft
4 - VbAlignRight
0 – VbAlignNone – Free floating toolbar
In toolbar some images are required to be displayed on
buttons. So, to get this image first of all imagelist should be
prepared for it.
* IMAGELIST :
Imagelist control allows to add bitmaps, that can be used by
other controls of the project. Image list control is also a part of
Microsoft windows common controls 6.0. so, if you have added this
component to you project than image list is also there in toolbox.
(So, First of all prepare a image list with bitmaps that you
want to display on button)
First step in creating toolbar is adding the images that will be
displayed on the toolbar.
To prepare an image list
1. Draw an imagelist control on your form and assign a unique
name to it. (If will appear as a small icon on the form)
2. Open property pages dialog box of image list by right-clicking
the image list selecting properties.
Select image page in the dialog box
Variables :
Syntax of variable declaration :
(Data type)
Dim variable name As variable type
Dim statement is used for declaring (dimensioning) variables.
Restrictions in naming variables :
1. The name must start with a letter, not a number or other
character.
2. Variable name can contain letters, number of under core
character. Spaces periods or other punctuation characters are
not allowed.
3. It must be unique within variable’s scope.
4. Maximum 255 characters can be there in var-name
5. It cannot be any of VB’s reserved words.
TYPES OF VARIABLES :
1 Integer 2 bytes -32, 768 to +32,767
2 Bytes 1 byte 0 to 255
3 Single 4 bytes Single precision nos.
4 Double 8 bytes Double precision nos.
5 Currency 8 bytes 15 fixed point nos. digits
before decimal point and 4
digits after decimal point.
6 String 1 byte per Maximum 65,400 char for
char fixed length sting & upto 2
billion characters for var-
length.
7 Boolean 2 bytes True / False
8 Date 8 bytes Date & time information
9 Object 4 bytes Instance of classes
10 Variant 16 bytes +
1 byte / char
User defined types can be created using type statement
Sytax
Private Type Type Name
Variable list
End type
Ex. Private Type Rectangle
Length As integer
Width As integer
End type
Dim My Rect as rectangle
My Rect. Length = 10
My Rect. Width = 5
Variable Declarations :
If a variable is not delared, VB create the variable using data
type, which can contain any type of data.
Draw backs – wastage of memory space
If might be invalid with fun that requires specific
data type.
There are two ways to declare a variable in to,
1. Explicit declaration :
Just defending variable names with their data types, without
assigning value to the variables.
Dim, private, static, public keywords can be used for explicit
declaration.
Dim varname as type, varnamez as type vanames as type.
2. Implicit declaration
In implicit declaration, a special characters is used at the end
of variable name where the variable is first assigned a value.
Scope of variables :
By default, a variable that is implicitly declared is local to the
procedure in which it is created with explicit declaration, scope of
variable can be defined.
For global declaration use public keyword in declaration
statement.
Ex. : Public uName as string
Variables declared as public var, are available anywhere in the
program. It is used to pass information between forms.
Local Variable :
Dim or private keywords are used to declare local variables.
If variable is declared with Dim statement than its local to the
current procedure if it is declared as private then it is local to
current form.
But it variable is defined in general declarations section of a
form or module then the variable is available to ever procedure in
that form.
Static variables :
Static variables are the variables that retains their value offer
the completion if procedure .
Ex : Static fact As integer
If function is declared as static then all the variables of that
function become static.
Variable Array :
Dim varname (Range) As varitype
Ex. Dim Roll_no (1 to 100) As Integer
Dim Marks (1 to 10) As Integer, count as integer
For Count = 1 to 10
Total = Total + marks (count)
Next count
Constant declaration
Constant is ta variable whose value cannot be changed once it
is defined.
Contents cannot be modified, after you define them. if you try to
modify. VB generates runtime errors.
Syntax :
Const varuname = value
Ex. Const pie = 3.142
Math Operations :
Addition +
Subtractim -
Multiplication *
Division /
Integer Division \
Modulus mod
Exponeatiotim ^
Ex.
MFCS – II
Visual Programming
Java Programming
DBMS
DCN
Total Percentage
Class
Calculate Result
CmdResult
CmdResult click ()
Dim MFCS As integer, VP As integer, JP As integer, DBMS As
integer, DCN As integer, Result as single
MFCS = Val (txtMFCS.text)
VP = Val (taxVP.text
JP = Val(txtJp.text)
DCN = Val (txtDCN.text)
Total % = MFCS + VP + JP + DBMS + DCN
Result = Total / 5
txt total.text = Result & “ % ”
If result > 70 then
Lbl class.captim “Distinction”
Else If Result > 60 Then
lblclass.captim = “First class”
Else If Result > 50 Then
lblclass.captim = “Second class”
Else If Result > 40 Then
lblclass.captim = “Pass class”
Else
lblclass.capion = “Fail”
End If.
OR
Select case Result
Case Is > 70
lblclass.capion =
Case 61 t0 70
lblclass.capion =
Case 51 t0 60
lblclass.capion =
Case iS > 40
lblclass.capion =
Case is < 40
lblclass.capion =
End case.
Example
First No.
Second No.
Simple Division
Integer division
Calculate
To search a string within any string, use insert function insert
returns starting position of the word.
Syntax
Instr (Start position, source string, search string, flag)
Optional
Flag = 0 default case sensitive search
Flag = 1 case insensitive search
String Factions :
(1) String $ ()
Retinues a string made up of a specific number of characters.
Syntax
String $ (No. of chair, “Character”)
(2) Instr() – Instr(Stat pos, string, serch str, flag
(3) InstrRev()-
(4) Left$ () – Left $ (String, No. of char)
(5) Right $() – Right $ (String, No. of char)
(6) Mid $ - Mid $ (String, Start pos, No. of char)
(7) Len () – Len (String)
(8) Replace – Replace (String, “original”, “New”)
(9) Trin $ - Trim $ (String)
(10) LTim$ - LTRim$ (String)
(11) RTrim$ - Rtcase$ (String)
(12) Ucase $ - Ucase$ (String)
(13) Lcase $ - Lcase$ (String)
(14) Space $ - Space $ (No of blank spaces)
(15) Str () - Str $ (Numeric value)
(16) Str Reverse $ ()
Ex :
Str$ = Input Box (“Enter your Branch Name”)
Ustr = VCase$ (Str)
Msg Box “Oh! You are the student of BCA!!”
End If
DATE FUNCTIONS :
(1) Now – Returns a varicant type of date/time stamp in timer
event with interval of 1000 ms.
Ex. – lb/time caption = Now
(2) Date() / Date $() – Returns date, In dd/mm/yy format & date
$ returns is string in dd-mm-yyyy format
Lbl.capim = data
(3) Time / Time$()
H : M : Second (AM/PM)
(4) Date Part () Return specified part of date.
Dim dtToday As Date
dtToday = Now
month % = Date Part (“m”, dt today )
day % = Date Part (“d”, dt today )
year % = year Part (“yyyy”, dt today )
dotweek % = Date Part (“q”, dt today )
week % = Date Part (“w”, dt today )
(5) Dim dt as date
Date = now
Date + 1
Date + 5
(6) Date : Diff() dtz = # 09/13/1981#
Dim dt1, dt2 as date dt = now
Date Diff. (“d”, dt2, dt1 )
(“m”, dt2, dt1 )
(“w”, dt2, dt1 )
(“yyyy”, dt2, dt1 )
(7) Date Add ()
dt = now
Date Add (“m”, 6, dt )
Date Add (“ww”, 9, dt )
Date Add (“d”, 180, dt )
- Ve number substracts date from given date
Format Functions :
(1) Format Currency ()
Format Currency (Expression, Num Dig its After Decinal,
Include leading digit, Use parents for negative, nums,
Group Digits)
Format Currency (100) = $100.00
(100, 3) = $100.000
(100, -1) = $100.00 [-1 for default]
(0.100, -1, Vbfalse) = $100
(0.100, -1, Vbfalse/Default) = $ 0.10
(-100, -1, Vbfalse) = -$100.00
(-100, -1, Vb True) = ($100.00)
(1100, -1, , Vb Default) = $1,100.00
(1100, -1, , ,Vb False) = $1100.00
(2) Format Number ()
Same as currency but without currency symbol
(3) Format percent ()
Format percent (1/3) = 33.33%
Format percent (1/3, 3) = 33.333%
(4) Format Date time ()
Vb General Date – mm/dd/yy H:M:Se AM/PM
Vb Long Date - Thursday, January 29, 2009
Vb Long Time - 8 : 38 : 07 AM
VB Short Date - 1 / 29 / 09
Vb Short time - 18 : 38
(5) Round ()
If no is odd Round up
If no is even Round down
Round (1.5) 2
Round (2.5) 2
Round (2.865, 2) 2.87
Round (2.865, 1) 2.9
lblresul
Class of then A
B
C
D
Total Amount
Calculate Bill
Discount
Default 0, 1, 2
Ce
nter
Right
Left
End Sub
India
Pakistan
Australia
Object.Add (Index, Key, text, icon small icon)
List view name.list items
1. Index – a number that position list item within list items
collection (optional)
2. Key – to assign name to list item
3. Text – string that is displayed in list view window
4. Icon – Index of icon in Image list for normal view
5. Smallicon – index of icon in “ for small view
Control Array :
A control away is a group of controls, all of the same type and
that have the same name are identified by an idex.
Each element must be of same type
Each control must have the same name
Each control is identified by unique index up to 32767
Advantages :
1. Requires fewer system resources then adding an individual
control of same type.
2. Controls of a array share a common set of event procedures.
3. It’s the only way to add controls to a forms at runtime.
4. More number of controls can be added in a form.
After crating a control away, a single piece of code can be
written to handle a particular event for all the controls in away.
Whenever that event is fired by any of the controls in array that
code is executed.
Ex. txtArray – lost focus (Index as integer)
txtArray (index) = Ucase (txtArray(index).text)
txtArray
Name : 0
Address : 1
City : 2
E-mail : 3
Option Explicit
Dim i As Integer
PARALLEL ARRAYS
Two or more difficult control arrays whose elements match
with each other in some way are known as parallel Array.
TABSTRIP :
Client Area
Example
Client Area
Experience
Name of firm :
Post :
Form load ()
Dim i as integer
For i = o to 2
Framel (i).move Tabstripl.clientleft, Tabstripl.clieatiop,
Tabstripl.clientwideth,Tabstripl.client Height
Next i
Frame 1 (0).Zorder 0
Tabstrip . click ()
Dim index, I as integer
Index = tabstripl.selected item. Index
For I = 0 + 2
Framel(i) . visible = false
Next i
Frame 1 (index – 1).Visible = True
End sub.
CONTROL ARRAY
CODE:
Option Explicit
Dim i As Integer
Private Sub Combo1_Click()
If Combo1.List(Combo1.ListIndex) = "CH" Then
i = txtArray.UBound + 1
Load lblArray(i)
Load txtArray(i)
txtArray(i).Top = txtArray(i - 1).Top + 500
lblArray(i).Top = lblArray(i - 1).Top + 500
lblArray(i).Alignment = 2
lblArray(i).Caption = "Subject 6"
txtArray(i).Visible = True
lblArray(i).Visible = True
End If
End Sub
This tutorial describes how you can use ADO objects in VB6. Now days, almost any
time you write full fledged database application you will want to use ADO. Along
with this, as your applications become more and more complex you will probably not
want to rely on Visual Basic's data controls, but instead use the ADO objects directly.
Read on to find out exactly how this can be done.
Prior to VB6 and the introduction of ADO (ActiveX Data Objects), VB programmers
would generally use DAO (Data Access Objects) to interact with local databases such
as MS Access and use RDO (Remote Data Objects) to interact with client/server
databases such as Oracle and SQL Server. The concept behind Visual Basic ADO was
Universal Data Access (UDA), where one database access method could be used for
any data source; it was designed to replace both DAO and RDO. DAO remains a
viable technology for interacting with MS Access databases as it is faster than ADO
for that purpose; however, ADO is more flexible – using ADO, one could develop a
prototype database application using MS Access in the back-end, and with a "flick of
the wrist" (i.e., with very little coding changes) "upsize" that same application to use
Oracle or SQL Server. As far as RDO is concerned, no new versions of it have been
developed beyond the version that shipped with Visual Basic, and there are no future
plans for it.
In the VB4 and VB5 worlds, RDO was the main method used to interact with
client/server databases. RDO works perfectly fine with VB6, so when folks migrated
their VB5 applications over to VB6, little or no coding changes were required.
However, ADO is the preferred method of database access for new VB6 applications .
This tutorial presents three small sample applications using ADO. All three
applications use a local MS Access database.
The first sample application introduces the ADO Data Control (ADODC) which
demonstrates a "quick and dirty" way to connect to a remote database. The second and
third applications use ADO code: the second allows navigation and searching of a
database table; the third allows navigation and updating on a database table. All three
connect to an ODBC Data Source, which must be set up through the Windows
Control Panel. How to do this is described below.
Note: If you have previously set up a DSN for the Biblio database as described in the
previous topic on RDO, you can skip the section on setting up an ODBC data source
and resume here.
Follow the steps below to set up an ODBC Data Source (this process is also called
"setting up a DSN", where "DSN" stands for "Data Source Name"). These steps
assume Windows 2000 for the operating system. On other versions of Windows, some
steps may vary slightly.
· Click the Add button. The Create New Data Source dialog box will appear.
Select Microsoft Access Driver (*.mdb) from the list and click the Finish button.
· The ODBC Microsoft Access Setup dialog box will appear. For Data Source
Name, type Biblio. If desired, you can type an entry for Description, but this is not
required.
· Click the Select button. The Select Database dialog box appears. On a default
installation of VB6 or Visual Studio 6, the BIBLIO.MDB sample database should
reside in the folder C:\Program Files\Microsoft Visual Studio\VB98. Navigate to that
folder, select BIBLIO.MDB from the file list, and click OK.
· When you are returned to the ODBC Microsoft Access Setup screen, the
database you selected should be reflected as shown below. Click OK to dismiss this
screen.
· When you are returned to the ODBC Data Source Administrator screen, the
new DSN should appear as shown below. Click OK to dismiss this screen.
At this point, the Biblio database is ready to be used with RDO in the sample
application.
· Start a new VB project, and from the Components dialog box (invoked from the
Project -> Components menu), select Microsoft ADO Data Control 6.0 (SPx) as
shown below and click OK.
The ADO Data Control should appear in your toolbox as shown below:
· Put an ADO Data Control on your form, and set the properties as follows:
Property
Value
Name
adoBiblio
DataSourceName
Biblio
SQL
· Now put three text boxes on the form, and set their Name, DataSource, and
DataField properties as follows:
Name
DataSource
DataField
txtAuthor
adoBiblio
Author
txtAuID
adoBiblio
Au_ID
txtYearBorn
adoBiblio
Year Born
· Save and run the program. Notice how it works just like the other data control.
· Now change the SQL property of the data control to select * from authors order
by author and run the program again. Notice the difference.
· Change the SQL property back to what it was and add three command buttons
to the form, and set their Name and Caption properties as follows:
Name
Caption
cmdNameOrder
Order by Name
cmdYearOrder
Order by Year
cmdIDOrder
Order by ID
· Put the following code in the cmdNameOrder_Click event:
adoBiblio.Refresh
adoBiblio.Refresh
adoBiblio.Refresh
· Save and run the program and see what happens when you click the buttons.
Note: If you have previously downloaded and set up a DSN for the Property database
as described in the previous topic on RDO, you can skip the set up steps below and
resume here.
The Property database contains just one table called "Property". The columns of this
table are defined as follows:
Column Name
Data Type
Notes
PROPNO
A number that uniquely identifies the property in the table. Should be treated as the
Primary Key (although it is not defined as such in the sample database).
EMPNO
A number that identifies the real estate agent selling the property. In a real system,
this would be the foreign key to the employee number in an Employee table (such a
table is not present in the sample database).
ADDRESS
Text (20)
CITY
Text (15)
STATE
Text (2)
ZIP
Text (5)
NEIGHBORHOOD
Text (15)
HOME_AGE
Age in years of the home. (A better table design choice would be to have this field be
the date in which the property was built and have the application compute the age
based on the current date.)
BEDS
Number (Long Integer)
BATHS
Number (Single)
Number of bathrooms in the property (allows for a decimal value such as 2.5,
indicating 2 ½ bathrooms – i.e. 2 full bathrooms and 1 "powder room").
FOOTAGE
ASKING
BID
SALEPRICE
Sale price (amount the property actually sold for) in whole dollars.
Before coding or running sample application 2 or 3, you must set up an ODBC data
source as was done for the previous sample application.
After downloading the file, move it to the folder of your choice. Then follow the exact
same steps as before to set up the DSN, with these two exceptions:
(1) On the ODBC Microsoft Access Setup dialog box, type PropDB for the Data
Source Name.
(2) In the Select Database dialog box, navigate to the location where you have placed
the PROPERTY.MDB file.
Sample Application 2
To build Sample Application 2, start a new VB project and perform the following
steps.
· From the Project -> References menu, check Microsoft ActiveX Data Objects
2.x (where x is the highest version that you have on your system) and click OK.
· This project uses the StatusBar control, so include the Microsoft Windows
Common Controls 6.0 (SP6) from the Components dialog box, accessed from the
Project -> Components menu.
· Create the form shown below. The names of the text boxes in the top frame are
shown in the form. Set the Enabled property of the frame to False, which will
automatically disable all of the textboxes within it, which is desired because this
application does not allow updating of the data. The settings for the other controls are
given below.
The navigation buttons have the following properties:
Name
Caption
cmdMoveFirst
<<
cmdMovePrevious
<
cmdMoveNext
>
cmdMoveLast
>>
The text box in the middle of the form has the following properties:
Name
txtCurrentQuery
MultiLine
True
Locked
True
Name
Caption
Enabled
cmdAllData
True
cmdGetData
False
Name
Caption
chkCriteria(0)
EmpNo
chkCriteria(1)
City
chkCriteria(2)
State
Name
Caption
Enabled
lblCriteria(0)
False
lblCriteria(1)
Like
False
lblCriteria(2)
Like
False
Caption
Enabled
txtCriteria(0)
EmpNo
False
txtCriteria(1)
City
False
txtCriteria(2)
State
False
Place the StatusBar on the form and set its Style property to 1 – sbrSimple.
2. Code the General Declarations section as shown below. Here, two ADO objects,
ADODB.Connection and ADODB.Recordset, are defined at the form level.
Option Explicit
3. Code the Form_Load event. Here, the connection object variable mobjADOConn is
made available for use by setting it to a new instance of ADODB.Connection. Then,
the ConnectionString property and the Open method of the ADODB.Connection
object are used.
'-----------------------------------------------------------------------------
'-----------------------------------------------------------------------------
mobjADOConn.ConnectionString = "DSN=PropDB;Uid=admin;Pwd=;"
mobjADOConn.Open
Call cmdAllData_Click
Exit Sub
LocalError:
End Sub
'-----------------------------------------------------------------------------
'-----------------------------------------------------------------------------
Call OpenNewRecordset
For lngX = 0 To 2
chkCriteria(lngX).Value = vbUnchecked
Next
Exit Sub
LocalError:
End Sub
Here, the recordset object mobjADORst is made available for use by setting (or
resetting) it to a new instance of ADODB.Recordset.
The CursorLocation property is then set to the built-in constant adUseClient. The term
"cursor" refers to the temporary rows of a recordset. The cursor location determines
whether the cursor is stored on the client or the server, specified by the values
adUseClient and adUseServer, respectively. Server-side cursor (adUseServer) is the
default. There are tradeoffs using both types of cursors. Client-side cursors can take a
long time to build because the data must be pulled over to the client, but once built,
traversing the cursor is usually very fast. Client-side cursors often support more
features than server-side cursors (the reason this sample application is using a client-
side cursor is because we want to use AbsolutePosition property later, which only
works with a client-side cursor). On the other hand, server-side cursors usually build
faster but often support fewer features that client-side cursors.
The Open method of the recordset is then executed. The Open method has the
following syntax:
RecordsetObject.Open Source, ActiveConnection, CursorType, LockType, Options
The Source argument is an optional variant that evaluates to a valid Command object,
SQL statement, table name, stored procedure call, or filename of a persisted recordset.
The CursorType argument is an optional value that determines the type of cursor that
the provider should use when opening the recordset. The possible values and their
descriptions are given below:
Value
Description
adOpenForwardOnly
adOpenStatic
Used to open a static cursor. A static cursor is a static copy of the data in the data
source. Once created, no changes made by other users propagate to the recordset; the
recordset never changes. Note: Client side cursors (like the one used in this sample
application) use only adOpenStatic for CursorTypes regardless of which CursorType
you select.
adOpenDynamic
Used to open a dynamic cursor. A dynamic cursor is a "live" recordset, meaning that
any and all additions, changes, and deletions by other users affect the recordset.
Dynamic-cursor recordsets support all types of navigation, including bookmarks (if
bookmarks are supported by the provider). Dynamic cursors offer the most features of
any cursor type, but at the expense of increased overhead.
adOpenKeyset
Used to open a keyset cursor. Keyset cursors are like dynamic cursors, except
additions made by other users are not visible in the recordset. The recordset is
affected by changes and deletions, however.
The LockType argument is an optional value that determines the type of locking that
the provider should use when opening the recordset. The possible values and their
descriptions are given below:
Value
Description
adLockReadOnly
(default) Specifies read-only locking. Records can be read, but data cannot be added,
changed, or deleted. This is the locking method used with static cursors and forward-
only cursors.
adLockPessimistic
adLockOptimistic
Specifies optimistic locking. The provider locks records only when you call the
Update method, not when you start editing.
adLockBatchOptimistic
Specifies optimistic batch locking. Records are locked in batch update mode, as
opposed to immediate update mode. This option is required for client-side cursors.
The Options argument is an optional Long value that indicates how the Source should
be evaluated. The possible values and their descriptions are given below:
Value
Description
adCmdText
adCmdTable
adCmdStoredProc
adCmdUnknown
Indicates that the type of command in the CommandText argument is not known and
that the provider should attempt to interpret it. Typically results in poor performance.
adExecuteAsync
adFetchAsync
Indicates that the remaining rows after the initial quantity specified in the CacheSize
property should be fetched asynchronously.
'-----------------------------------------------------------------------------
'-----------------------------------------------------------------------------
txtCurrentQuery.Text = mstrSQL
End Sub
6. Create the user-defined subprocedure DataLoad. This subprocedure gets the data
from the recordset and puts each field into a text box. Data from the recordset is
accessed via the Fields collection.
The Fields collection in ADO works identically to the Fields collection in DAO. A
field can be referenced with or without specifying Fields, either by the field name in
quotes or by its ordinal position in the resultset. The field can also be referenced with
the bang (!) operator. All of the following would be valid ways of referencing the
field "propno":
mobjADORst.Fields("propno")
mobjADORst ("propno")
mobjADORst.Fields(0)
mobjADORst(0)
mobjADORst!propno
'-----------------------------------------------------------------------------
'-----------------------------------------------------------------------------
On Error GoTo LocalError
txtPropNo.Text = mobjADORst.Fields("propno")
txtEmpNo.Text = mobjADORst.Fields("empno")
txtAddress.Text = mobjADORst.Fields("address")
txtCity.Text = mobjADORst.Fields("city")
txtState.Text = mobjADORst.Fields("state")
txtZip.Text = mobjADORst.Fields("zip")
Call SetRecNum
Exit Sub
LocalError:
End Sub
7. Create the user-defined subprocedure SetRecNum. This sub displays the number of
the current record at the bottom of the screen. The AbsolutePosition and RecordCount
properties of the Recordset are used here.
The AbsolutePosition property specifies the current row in a recordset. Note: For
AbsolutePosition to return a valid value with Access (Jet) databases (like the one used
in the sample application), the CursorLocation must be set to adUseClient. An invalid
value (-1) will be returned if adUseClient is specified.
The RecordCount property the total number of rows in the recordset. Note:
RecordCount will not return a valid value with all cursor types (for example,
RecordCount will return -1 with a forward-only cursor.) To ensure a valid
RecordCount value, use either adOpenKeyset or adOpenStatic as the CursorType for
server side cursors or use a client side cursor.
'-----------------------------------------------------------------------------
'-----------------------------------------------------------------------------
End Sub
8. Code the events for the navigation buttons as shown below, using the recordset
"Move" methods to move to the first, last, next, or previous record, respectively.
'-----------------------------------------------------------------------------
'-----------------------------------------------------------------------------
mobjADORst.MoveFirst
Call DataLoad
Exit Sub
LocalError:
End Sub
'-----------------------------------------------------------------------------
mobjADORst.MoveLast
Call DataLoad
Exit Sub
LocalError:
End Sub
'-----------------------------------------------------------------------------
'-----------------------------------------------------------------------------
mobjADORst.MoveNext
If mobjADORst.EOF Then
Beep
mobjADORst.MoveLast
End If
Call DataLoad
Exit Sub
LocalError:
End Sub
'-----------------------------------------------------------------------------
'-----------------------------------------------------------------------------
mobjADORst.MovePrevious
If mobjADORst.BOF Then
Beep
mobjADORst.MoveFirst
End If
Call DataLoad
Exit Sub
LocalError:
End Sub
9. When one of the check boxes is clicked, the label and text box next to it should be
enabled (or disabled, if clicking the check box unchecks it). Note also that the
cmdGetData button (the one with the "Run Query Now" caption) should only be
enabled if one of the checkboxes is checked.
'-----------------------------------------------------------------------------
'-----------------------------------------------------------------------------
'when the user clicks on a check box, enable the label and text
txtCriteria(Index).Enabled = True
lblCriteria(Index).Enabled = True
txtCriteria(Index).SetFocus
txtCriteria(Index).SelStart = 0
txtCriteria(Index).SelLength = Len(txtCriteria(Index).Text)
' enable the 'Run Query Now' button only if a box is checked.
cmdGetData.Enabled = True
Else
txtCriteria(Index).Enabled = False
lblCriteria(Index).Enabled = False
End If
End Sub
10. After the user has selected which fields to use and entered values in the text boxes,
they click the cmdGetData button to create a new recordset with new data. Note that if
the user selects (checks) a field, but does not enter search criteria in the corresponding
textbox, an error message is generated and the query is not run.
'-----------------------------------------------------------------------------
'-----------------------------------------------------------------------------
'run the query that the user has created
blnFirstOne = True
vbExclamation, _
"ADO Example"
Exit Sub
End If
blnFirstOne = False
End If
vbExclamation, _
"ADO Example"
Exit Sub
End If
End If
blnFirstOne = False
mstrSQL = mstrSQL & " city like '" & txtCriteria(1).Text & "'"
End If
vbExclamation, _
"ADO Example"
Exit Sub
End If
End If
blnFirstOne = False
mstrSQL = mstrSQL & " state like '" & txtCriteria(2).Text & "'"
End If
OpenNewRecordset
If mobjADORst.EOF Then
MsgBox "Your query (" & mstrSQL & ") returned no records! " _
& "The default query to return all records will now be rerun.", _
vbExclamation, _
"ADO Example"
'reload the form with all the records
cmdAllData_Click
Else
MsgBox "Your query returned " & mobjADORst.RecordCount & " records.", _
vbInformation, _
"ADO Example"
Call DataLoad
End If
Exit Sub
LocalError:
End Sub
11. Save and run. Note: When entering the "Like" criteria for City and/or State, you
can use the wildcard character % to represent any number of characters and the
wildcard character _ (underscore) the represent a single character. For example,
entering "M%" for the City criteria would return all rows where the city field begins
with the letter "M".
Sample Application 3
Sample Application 3 demonstrates how to add, update, and delete records with ADO.
When the application is first run, the user is prompted to enter a minimum asking
price to possibly limit the number of records they want to work with (i.e., "I only want
to work with properties that are selling for $200,000 or more). If the user wants to
work with all properties, they would simply accept the default of 0 from the prompt.
If the user clicks the Cancel button, the application will end.
Once the user has entered the minimum asking price, the main screen of the
application is displayed. Initially, the screen is in "browse" mode, where the user can
use the navigation buttons to move to the first, previous, next or last record. The data
cannot be edited in this mode. If they want to initiate an add or an update, delete a
record, or exit the application, they may do so via the appropriate button. Saving or
cancelling is not applicable in this mode, so those buttons are disabled.
If the user clicks the Add button, the fields on the screen are enabled and cleared, and
the user can enter the information for the new property. All buttons except Save and
Cancel are now disabled. After the user has made entries in the fields, he or she would
click Save to add the new record to the database table, or, if they changed their mind,
would click Cancel to discard the new record. In either case (clicking Save or Cancel)
the user is returned to browse mode. When Save is clicked, the application validates
the entries and will only save the record if all fields pass edit (otherwise, a message
will appear indicating the problem entry and focus will be set to the problem field).
If the user clicks the Update button, the fields on the screen are enabled and the user
can modify any or all of the fields (except for the Property Number, which is the
primary key of the table). All buttons except Save and Cancel are now disabled. After
the user has made modifications in the desired fields, he or she would click Save to
update the record to the database table, or, if they changed their mind, would click
Cancel to discard the changes. In either case (clicking Save or Cancel) the user is
returned to browse mode. When Save is clicked, the application validates the entries
and will only save the record if all fields pass edit (otherwise, a message will appear
indicating the problem entry and focus will be set to the problem field).
If the user clicks the Delete button, the user is asked to confirm that they want to
delete the current record. If they respond Yes, the record is deleted from the database
table, and the main screen shows the next record in the table.
To build Sample Application 3, start a new VB project and perform the following
steps.
· From the Project -> References menu, check Microsoft ActiveX Data Objects
2.x Library and click OK.
· This project uses the StatusBar control, so include the Microsoft Windows
Common Controls 6.0 (SP6) from the Components dialog box, accessed from the
Project -> Components menu. Check this item and click OK.
· Create the form shown below. The settings for the various controls are given
below.
· There are nine textboxes in the main frame of the form. The names and
MaxLength settings for these are given below:
Name
Properties
txtPropNo
MaxLength: 5
txtEmpNo
MaxLength: 4
txtAddress
MaxLength: 20
txtCity
MaxLength: 15
txtState
MaxLength: 2
txtZip
MaxLength: 5
txtBeds
MaxLength: 1
txtBaths
txtAsking
Caption
cmdMoveFirst
<<
cmdMovePrevious
<
cmdMoveNext
>
cmdMoveLast
>>
cmdAdd
Add
cmdUpdate
Update
cmdDelete
Delete
cmdSave
Save
cmdCancel
Cancel
cmdExit
Exit
· All controls on your form should have their TabIndex property set such that the
tabbing order is correct.
· Add a Module to the project, name it modCommon, and enter the code shown
below. The code contains procedures described as follows:
CenterForm
ValidKey
ConvertUpper
SelectTextBoxText
Sub to highlight the text of a textbox when it receives focus. Used in the GotFocus
event of a textbox.
TabToNextTextBox
Sub to "autotab" from one textbox to another when maximum number of characters
that can be entered into the first textbox has been reached.
UnFormatNumber
Function to strip out non-numeric characters (dollar signs, commas, etc.) from a
formatted number.
Option Explicit
'------------------------------------------------------------------------
'------------------------------------------------------------------------
With pobjForm
End With
End Sub
'------------------------------------------------------------------------
'------------------------------------------------------------------------
' Common function to filter out keyboard characters passed to this
'
'
If pintKeyValue < 32 _
Else
pintKeyValue = 0
End If
ValidKey = pintKeyValue
End Function
'------------------------------------------------------------------------
'------------------------------------------------------------------------
'
pintKeyValue = pintKeyValue - 32
End If
ConvertUpper = pintKeyValue
End Function
'-----------------------------------------------------------------------------
'-----------------------------------------------------------------------------
With pobjTextbox
.SelStart = 0
.SelLength = Len(.Text)
End With
End Sub
'-----------------------------------------------------------------------------
'-----------------------------------------------------------------------------
pobjTextBox2.SetFocus
End If
End Sub
'-----------------------------------------------------------------------------
'-----------------------------------------------------------------------------
strNumberOut = ""
End If
Next
UnFormatNumber = strNumberOut
End Function
· Code the General Declarations section as shown below. Here, as in the previous
sample application, two ADO object variables, mobjADOConn and mobjADORst, are
defined at the form level, as are some other form-level variables that will be needed.
Option Explicit
'-----------------------------------------------------------------------------
'-----------------------------------------------------------------------------
' obtain the minimum asking price for the properties to be worked with
GetMinimumAsking
CenterForm Me
mobjADOConn.ConnectionString = "DSN=PropDB;Uid=admin;Pwd=;"
mobjADOConn.Open
Call GetPropertyData
SetFormState False
Exit Sub
LocalError:
End Sub
Code the GetMinimumAsking Sub, which uses the InputBox function to prompt to
the user to enter the minimum asking price of the properties they want to work with.
The resulting value is then stored in the form-level variable mdblMinAsking.
'-----------------------------------------------------------------------------
'-----------------------------------------------------------------------------
strInputBoxPrompt = "Enter the minimum asking price (for example, 200000) " _
& "for the properties that you want to work with this session." _
& vbNewLine _
& "To work with ALL properties, leave the default of zero."
' user clicked Cancel button on the input box, so end the app
End
End If
mdblMinAsking = Val(strAsking)
End Sub
Code the GetPropertyData Sub, which builds the SQL to get the property records
meeting the minimum asking price condition. The Recordset object is then
instantiated, its CursorLocation property is set, and its Open method is invoked to
execute the SQL and return the resultset. This is done in a loop in case the resultset
does not return any records due to the fact no records in the table met the asking price
condition. In that situation, the user is given the opportunity to specify a different
asking price value. Following this, the programmer-defined Sub PopulateFormFields
is called (which displays the fields from the current record in their corresponding
textboxes on the form).
'-----------------------------------------------------------------------------
'-----------------------------------------------------------------------------
blnGotData = False
Do
mobjADORst.CursorLocation = adUseClient
If mobjADORst.EOF Then
vbYesNo + vbQuestion, _
"Asking Price") _
= vbYes Then
GetMinimumAsking
Else
End
End If
Else
blnGotData = True
End If
Loop Until blnGotData
Call PopulateFormFields
Exit Sub
LocalError:
End Sub
Code the PopulateFormFields Sub, which assigns the fields from the current record to
their corresponding textboxes on the form. Note that the gblnPopulating Boolean
variable is set to True prior to the assignments and set to False after the assignments.
This value is used to control whether or not certain code executes in the event
procedures for some of these textboxes. The Sub SetRecNum is then called.
'-----------------------------------------------------------------------------
'-----------------------------------------------------------------------------
gblnPopulating = True
txtPropNo.Text = mobjADORst.Fields("propno")
txtEmpNo.Text = mobjADORst.Fields("empno")
txtAddress.Text = mobjADORst.Fields("address")
txtCity.Text = mobjADORst.Fields("city")
txtState.Text = mobjADORst.Fields("state")
txtZip.Text = mobjADORst.Fields("zip")
txtBeds.Text = mobjADORst.Fields("beds")
txtBaths.Text = mobjADORst.Fields("baths")
gblnPopulating = False
Call SetRecNum
Exit Sub
LocalError:
End Sub
Code the SetRecNum Sub. This sub is identical to the one used in Sample Application
2. It displays the number of the current record at the bottom of the screen using the
AbsolutePosition and RowCount properties of the Recordset object.
'-----------------------------------------------------------------------------
'-----------------------------------------------------------------------------
End Sub
Code the SetFormState Sub, which takes in a Boolean argument used to set the
Enabled property of the controls on the form. Based on whether the value True or
False is passed to this sub, this sub ensures that the textboxes are enabled for adds and
updates and disabled for browsing; it also ensures that the various command buttons
are enabled or disabled at the appropriate time. This Sub also sets the form-level
Boolean variable mblnUpdatePending.
'-----------------------------------------------------------------------------
'-----------------------------------------------------------------------------
txtPropNo.Enabled = pblnEnabled
txtEmpNo.Enabled = pblnEnabled
txtAddress.Enabled = pblnEnabled
txtCity.Enabled = pblnEnabled
txtState.Enabled = pblnEnabled
txtZip.Enabled = pblnEnabled
txtBeds.Enabled = pblnEnabled
txtBaths.Enabled = pblnEnabled
txtAsking.Enabled = pblnEnabled
cmdSave.Enabled = pblnEnabled
cmdCancel.Enabled = pblnEnabled
mblnUpdatePending = pblnEnabled
End Sub
'-----------------------------------------------------------------------------
'-----------------------------------------------------------------------------
If mblnUpdatePending Then
MsgBox "You must save or cancel the current operation prior to exiting.", _
vbExclamation, _
"Exit"
Cancel = 1
Else
End If
End Sub
Code the events for the various Textboxes as shown below. The code in these events
ensure the following:
· For all, highlight the text in the textbox when it receives focus.
· For all but the last textbox, if the maximum number of characters typed into the
textbox is reached, auto-tab to the next textbox.
· Only numeric digits should be entered into the property number, employee
number, zip codes, and beds textboxes.
· Only numeric digits and optionally one decimal point should be entered into the
baths and asking textboxes.
· When the asking textbox receives focus, the value in there should be
unformatted. When the asking textbox loses focus, its value should be formatted as
currency.
'-----------------------------------------------------------------------------
'-----------------------------------------------------------------------------
' property #
SelectTextBoxText txtPropNo
End Sub
End Sub
End Sub
' emp #
SelectTextBoxText txtEmpNo
End Sub
End Sub
End Sub
' address
SelectTextBoxText txtAddress
End Sub
End Sub
' city
SelectTextBoxText txtCity
End Sub
End Sub
' state
SelectTextBoxText txtState
End Sub
KeyAscii = ConvertUpper(KeyAscii)
End Sub
End Sub
' zip
SelectTextBoxText txtZip
End Sub
End Sub
' beds
SelectTextBoxText txtBeds
End Sub
End Sub
End Sub
' baths
SelectTextBoxText txtBaths
End Sub
' if text already has a decimal point, do not allow another ...
KeyAscii = 0
End If
End Sub
End Sub
txtAsking.Text = UnFormatNumber(txtAsking.Text)
SelectTextBoxText txtAsking
End Sub
' if text already has a decimal point, do not allow another ...
KeyAscii = 0
End If
End Sub
End Sub
Code the events for the navigation buttons as shown below, using the resultset
"Move" methods to move to the first, last, next, or previous record, respectively.
'-----------------------------------------------------------------------------
'-----------------------------------------------------------------------------
Call PopulateFormFields
Exit Sub
LocalError:
End Sub
'-----------------------------------------------------------------------------
'-----------------------------------------------------------------------------
mobjADORst.MoveLast
Call PopulateFormFields
Exit Sub
LocalError:
End Sub
'-----------------------------------------------------------------------------
'-----------------------------------------------------------------------------
mobjADORst.MoveNext
If mobjADORst.EOF Then
Beep
mobjADORst.MoveLast
End If
Call PopulateFormFields
Exit Sub
LocalError:
End Sub
'-----------------------------------------------------------------------------
'-----------------------------------------------------------------------------
mobjADORst.MovePrevious
If mobjADORst.BOF Then
Beep
mobjADORst.MoveFirst
End If
Call PopulateFormFields
Exit Sub
LocalError:
End Sub
Code the Click event for the cmdAdd button. In it, the textboxes are cleared, the
SetFormState sub is called (passing it a parameter of True, which will enable the
textboxes and the Save and Cancel buttons and disable all the other buttons), set the
form-level variable mstrUpdateType to "A" (indicating that an add is pending) and
sets focus to the Property Number field.
'-----------------------------------------------------------------------------
'-----------------------------------------------------------------------------
txtPropNo.Text = ""
txtEmpNo.Text = ""
txtAddress.Text = ""
txtCity.Text = ""
txtState.Text = ""
txtZip.Text = ""
txtBeds.Text = ""
txtBaths.Text = ""
txtAsking.Text = ""
SetFormState True
mstrUpdateType = "A"
txtPropNo.SetFocus
Exit Sub
LocalError:
MsgBox Err.Number & " - " & Err.Description
End Sub
Code the Click event for the cmdUpdate button. In it, the SetFormState sub is called
(passing it a parameter of True, which will enable the textboxes and the Save and
Cancel buttons and disable all the other buttons), set the form-level variable
mstrUpdateType to "U" (indicating that an update is pending), disables the Property
Number field (because it is the primary key and should not be changed) and sets focus
to the Employee Number field.
'-----------------------------------------------------------------------------
'-----------------------------------------------------------------------------
SetFormState True
mstrUpdateType = "U"
' being that propno is the primary key, it should not be updatable
txtPropNo.Enabled = False
txtEmpNo.SetFocus
Exit Sub
LocalError:
End Sub
Code the Click event for the cmdSave button. The user would click this button after
they have completed entries for an add or update. This sub first invokes the
ValidateAllFields function, which returns a Boolean indicating whether or not all
entries passed their edit checks. If not, we exit the sub and the record is not saved; the
user remains in "update pending" mode and has the opportunity to correct the entries.
Provided that validation is successful, the sub proceeds. The mstrUpdateType variable
is checked to see whether we are dealing with an add or an update.
If we are dealing with an add, we invoke the AddNew method of the Recordset
object. The AddNew method prepares a new row you can edit and subsequently add
to the Recordset object using the Update method. After you modify the new row, you
must use the Update method to save the changes and add the row to the result set. No
changes are made to the database until you use the Update method. (The Update
method is invoked after the content of the textboxes has been assigned to the database
fields.)
If we are dealing with an update, we can just start modifying the fields (provided an
appropriate cursor type has been selected) – unlike DAO and RDO, ADO does not
use an Edit method. Changes made to the current row’s columns are copied to the
copy buffer. After you make the desired changes to the row, use the Update method to
save your changes or the CancelUpdate method to discard them. (If you move on to
another record without invoking Update, your changes will be lost.)
The content of the textboxes is assigned to the database fields, then the Update
method is invoked. The Update method saves the contents of the copy buffer row to a
specified updatable Recordset object and discards the copy buffer.
The mstrUpdateType variable is checked once again, and if we are dealing with an
add, there is some extra work to do. Although the new record has been added, the
original resultset still does not contain the new record. The Requery method must be
invoked, which updates the data in a Recordset object by re-executing the query on
which the object is based. The Find method is then used to position to the new record.
The ADO Find method has the following syntax:
The Criteria argument is a String value that specifies the column name, comparison
operator, and value to use in the search. Only a single-column name may be specified
in criteria; multi-column searches are not supported. The comparison operator may be
">" (greater than), "<" (less than), "=" (equal), ">=" (greater than or equal), "<=" (less
than or equal), "<>" (not equal), or "like" (pattern matching). The value may be a
string, floating-point number, or date. String values are delimited with single quotes
or "#" (number sign) marks (for example, "state = 'WA'" or "state = #WA#"). Date
values are delimited with "#" (number sign) marks (for example, "start_date >
#7/22/97#"). These values can contain hours, minutes, and seconds to indicate time
stamps, but should not contain milliseconds or errors will occur. If the comparison
operator is "like", the string value may contain an asterisk (*) to find one or more
occurrences of any character or substring. For example, "state like 'M*'" matches
Maine and Massachusetts. You can also use leading and trailing asterisks to find a
substring contained within the values. For example, "state like '*as*'" matches Alaska,
Arkansas, and Massachusetts. Asterisks can be used only at the end of a criteria
string, or together at both the beginning and end of a criteria string, as shown above.
You cannot use the asterisk as a leading wildcard ('*str'), or embedded wildcard
('s*r'). This will cause an error.
SkipRows is an optional Long value, whose default is zero, that specifies the row
offset from the current row (or bookmark row specified by the Start argument, if
present) to begin the search. By default, the search will start on the current row.
Start is an optional Variant bookmark that functions as the starting position for the
search.
Note: Unlike DAO, ADO does not have a "NoMatch" property. If the ADO Find
method is unsuccessful, the record pointer is positioned at the end of the Recordset.
The SetRecNum sub is then be called to display the status bar information about the
new record. The SetFormState sub is then called with a parameter of False, which
causes the textboxes and the Save and Cancel buttons to be disabled and all other
buttons to be enabled.
Note that in the statement that assigns the contents of the txtAsking textbox to the
asking field of the table, our UnFormatNumber function is used to strip off the non-
numeric characters. This is because we are using a display format that includes a
dollar sign and commas on the txtAsking control, and an error would occur if we
attempted to assign this directly to the asking field, which is defined as numeric.
'-----------------------------------------------------------------------------
'-----------------------------------------------------------------------------
Else
End If
mobjADORst.Fields("propno") = txtPropNo.Text
mobjADORst.Fields("empno") = txtEmpNo.Text
mobjADORst.Fields("address") = txtAddress.Text
mobjADORst.Fields("city") = txtCity.Text
mobjADORst.Fields("state") = txtState.Text
mobjADORst.Fields("zip") = txtZip.Text
mobjADORst.Fields("beds") = txtBeds.Text
mobjADORst.Fields("baths") = txtBaths.Text
mobjADORst.Fields("asking") = UnFormatNumber(txtAsking.Text)
mobjADORst.Update
mobjADORst.Requery
SetRecNum
End If
Reset:
SetFormState False
Exit Sub
LocalError:
Resume Reset
End Sub
Code the Click event for the cmdDelete button. The user is first asked to confirm that
they want to delete the record, and if so, the Delete method of the resultset object is
invoked, which deletes the current row in an updatable resultset object. The Requery
method is then invoked so that the record is removed from the resultset that the user is
working with. The Find method is then invoked to position the next record after the
deleted one. If it was the last record that was deleted, then we position to the "new"
last record using the MoveLast property. PopulateFormFields must then be called to
display the contents of the new current record.
'-----------------------------------------------------------------------------
'-----------------------------------------------------------------------------
'when the current record is deleted, the current location in the recordset
'is invalid. use the Requery method to re-execute the query and update
'the data.
vbYesNo + vbQuestion, _
End If
mobjADORst.Delete
mobjADORst.Requery
' If it was the last record that was deleted, the Find method will
' come back with EOF, in which case we should MoveLast to position
Call PopulateFormFields
Exit Sub
LocalError:
End Sub
'-----------------------------------------------------------------------------
txtPropNo.SetFocus
Exit Function
vbExclamation, _
"Property #"
txtPropNo.SetFocus
Exit Function
End If
End If
txtEmpNo.SetFocus
Exit Function
End If
Exit Function
End If
txtCity.SetFocus
Exit Function
End If
txtState.SetFocus
Exit Function
End If
' it's OK
Else
vbExclamation, _
"Zip Code"
txtZip.SetFocus
Exit Function
End If
If Val(txtBeds.Text) = 0 Then
txtBeds.SetFocus
Exit Function
End If
If Val(txtBaths.Text) = 0 Then
txtBaths.SetFocus
Exit Function
End If
If Val(UnFormatNumber(txtAsking.Text)) = 0 Then
txtAsking.SetFocus
Exit Function
End If
ValidateAllFields = True
End Function
'--------------------------------------------------------------------------------
'--------------------------------------------------------------------------------
blnStateFound = False
Exit For
End If
Next
ValidState = blnStateFound
End Function
'-----------------------------------------------------------------------------
'-----------------------------------------------------------------------------
strSQL = "select count(*) as the_count from property where propno = " &
txtPropNo.Text
PropertyExists = True
Else
PropertyExists = False
End If
End Function
Code the Click event for the cmdCancel button. The user would click this button if,
during an add or update, they decide to abandon the operation. Here,
PopulateFormFields is called to reset the textboxes to their content prior to the user
clicking the Add or Update button, and SetFormState is called with a parameter of
False, which causes the textboxes and the Save and Cancel buttons to be disabled and
all other buttons to be enabled.
'-----------------------------------------------------------------------------
'-----------------------------------------------------------------------------
PopulateFormFields
SetFormState False
End Sub
Code the Click event for the cmdExit button, which issues the Unload Me statement
to fire the Form_Unload event, which will unload the form and end the application.
'-----------------------------------------------------------------------------
'-----------------------------------------------------------------------------
Unload Me
End Sub