You are on page 1of 72

T HC VISUAL BASIC 6.

0 - PHN 3

MC LC
Dng Ha (Phn II) ................................................................................. 3
Dng Ha (Phn III) .............................................................................. 12
C s d liu (Database) ............................................................................. 23
Dng Control Data ...................................................................................... 35
Lp trnh vi k thut DAO .......................................................................... 46
Lp trnh vi ADO (phn I) .......................................................................... 58

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

Dng Ha (Phn II)


In trn mn nh
VB6 c method Print cho ta in thng trn Form, PictureBox hay Printer. Ba loi
control ny c coi nh nhng khung vi m ha s v ln.
Bn hy khi ng mt chng trnh VB6 mi. t ln form mt PictureBox tn
Picture1 v mt button tn CmdPrintTenLines vi Caption Print Ten Lines.
DoubleClick ln button ny v vit code di y:
Private Sub CmdPrintTenLines_Click()
Dim i As Integer
' String variable used for display
Dim strLine As String
' Write 10 lines, one under the other
For i = 1 To 10
strLine = "This is line " & CStr(i)
Me.Print strLine ' Print on Form
Picture1.Print strLine ' Print on Picture1
Next
End Sub

Bn hy chy th program ri click nt Print Ten Lines. Trong trng hp ny


ta dng default Font v Color in 10 hng. Sau mi Print, chng trnh t ng
xung hng.
K , thm mt button tn CmdPrintFontSizes vi Caption Print Font Sizes.
DoubleClick ln button ny v vit code di y:
Private Sub CmdPrintFontSizes_Click()
Dim i As Integer
' Print numbers 1 to 10, one after the other on the same line
For i = 1 To 10
' Define Font size
Me.Font.Size = Me.Font.Size + i
' Define Color using Function QBColor
Me.ForeColor = QBColor(i)
' Print without moving to next line. Note the semicolon ";"
Me.Print Str(i);
Next
End Sub

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

Trong Sub CmdPrintFontSizes_Click, ta thay i c kiu ch cho cc con s


c in ra ln ln dn dn v thay i mu ca cc con s bng cch dng
function QBColor. in cc con s lin tc khng xung hng ta dng method
Print vi semicolon (;). Bn hy chy chng trnh li. Click nt Print Ten Lines
ri click nt Print Font Sizes, kt qu s ging nh di y:

By gi bn th minimize ca s ca chng trnh, k restore n li kch


thc c. Bn s thy cc hng ta in lc ny khng cn trong form hay
PictureBox na.
L do l khi ta Print ln form hay PictureBox, cc hnh y c v trong graphic
a phng ch khng c VB6 k l mt phn ca ca s. Mun trnh tr ngi
ny ta phi dn VB6 nh v li bng cch set property AutoRedraw ca form
v Picture1 ra True.

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

H thng ta
Khi t mt Object hay v mt ci g ln mn nh (screen) hay form .v.v.. ta cn
phi ch nh Object y nm ch no k t (with reference to) ci gc Trn Tri
(Top Left) ca mn nh hay form.
Ci gc Trn Tri l Trung tm ta ca screen hay form. ta X v Y
u bng 0, ta vit l 0,0. Nu ta i ln qua phi theo chiu rng ca screen th
ta X tng ln. Nu ta i dc xung di theo chiu cao ca screen th ta
ca Y tng ln.
K n l n v o lng ta dng biu din khong cch. Trong bi trc ta
ni n mn ca mn nh (screen resolution) da vo pixel. Ta c th
dng n v pixel ni mt Object c ta X v Y mi chiu bao nhiu pixels
tnh t trung tm ta .
Nh th, ngay c trn cng mt mn nh khi ta tng mn n ln th mt
Object c t ln mn nh theo n v pixel s xch qua tri v ln trn
mt t v kch thc mt pixel by gi nh hn lc trc mt cht.
Hnh di y minh ha cc kch thc ca mn nh v Form.

im cn bit l c nhng phn nh title bar v border ca mt form ta khng


th v ln c. Do din tch cn li ca form c gi l Client Area. Chiu
rng v chiu cao ca Client Area c gi l ScaleWidth v ScaleHeight.
Nu mun khong cch t mt Object n trung tm ta , hay kch thc ca
chnh Object, khng h thay i d ta c tng, gim mn ca mn nh hay in
hnh ra printer (th d ta mun n lun lun di 5cm chng hn) th ta dng h
thng ta theo n v twips ca form.

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

Twips l Default Coordinate System ca VB6. Trong h thng ny mi im l


tng ng vi 1/567 centimeter. Do , nu bn v mt dng di 567 twips
n s hin th di 1cm trn mn nh, v khi bn in n ra, n cng di 1cm trn
giy. Tc l di tht ca Object khng ty thuc vo loi mn nh ( mn
cao hay thp) hay printer. Ngi ta ni n l Device independent coordinate
system (H thng ta c lp vi dng c). Ni mt cch khc Twips cho ta
tht s what you see is what you get (WYSIWYG - thy sao c vy), rt
thch hp vi Desktop publishing.
Bn c th thay i h thng ta ca mt form bng cch edit property
ScaleMode qua ca s Properties nh sau:

Ghi ch: Thay i tr s ScaleMode khng c hiu lc ngay m ch nh hng


nhng g c thit k sau .
Ging nh khi ta Edit Text trong Notepad, Text Cursor (thanh | chp chp) l v
tr hin ti, ni s hin th ci ch ta nh sp ti, trong graphic ta c mt
Cursor v hnh, ni s hin th ci g ta sp Print. Ta ch nh v tr ca graphic
cursor y bng cch cho tr s ca CurrentX v CurrentY.
Bn hy khi ng mt d n VB6 mi v vit code cho Event Resize ca form
chnh nh sau:

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

Th chy chng trnh v Resize form. Mi khi bn Resize form, ch X s c


di n v tr khong chnh gia ca Client Area ca form.

Dng Graphics
c mt cht cn bn v graphics ca VB6, by gi ta c th t nhng
graphics ln form. C hai cch lm chuyn y:

Dng Graphical Controls: Ta c PictureBox v Image c th cha


hnh nh. Trong khi Line v Shape c th v ng thng hay cc hnh
ch nht, trn .v.v.. trn form, lc thit k.
Dng Graphics Methods: y l nhng mnh lnh cho ta v trc tip
ln form lc run-time. Cc mnh lnh VB6 cho ta l Cls, Pset, Point,
Line v Circle.

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

Ty theo hon cnh, bn c th la chn cch no tin dng.

PictureBox v Image
Dng PictureBox hay Image l cch d nht hin th mt graphic trong form.
Lc thit k, bn c th nh thng tn ca graphic vo property Picture trong
ca s Properties. Form cng nhn property Picture. Bn cng c th click ln
bn phi ch property Picture browse v chn mt graphic, thng l Bitmap
hay Icon.

S khc bit ch gia Image v PictureBox l Image c property Stretch m ta


c th set thnh True ko dn graphic ra cho chim trn din tch ca Image.
Image l mt grapgic control lightweight (nh k), tc l n khng i hi
nhiu memory v chy nhanh hn PictureBox. L do l PictureBox l mt
container, tc l n c th cha cc controls khc. Ngoi ra, PictureBox cng cho
php ta v ln trn n ging nh trn form.

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

Trong hnh di y, trong lc thit k ta t mt PictureBox v mt Image cng


mt c ln cng mt form. K ta assign cng mt picture hnh happy.bmp
cho c hai. Ring vi Image, ta set property Stretch ca n ra True.

Ch nh hnh nh lc run-time
Trong lc program ang chy, ta c th thay i hnh nh cha trong PictureBox
hay Image bng cch dng Function LoadPicture. Nh l ta khng th assign
trc tip vo Property Picture ca hai graphical controls ny. L do l Property
Picture ch l mt cch thn thin cho ta ch nh mt graphic trong lc thit k.
Khi mt hnh nh c ch nh ri, VB6 cha c hnh y vo file c cng tn
vi file ca form nhng vi extension .frx. Tc l nu tn ca form l Form1 th
graphic ca Property Picture c cha chung vi cc graphics khc ca form
trong file Form1.frx.
Do , v VB6 program cha lun graphic chung vi n, ta khng cn phi nhc
n tn ca graphic file khi dng hay deploy, tc l khng cn nh km tn
graphic file trong Setup file cho ngi ta install. Di y l code mu lc
run-time ta load mt graphic tn sad.bmp nm trong Subfolder tn images ca
App.path vo Image control tn Image1.
Private Sub CmdLoad_Click()
Dim LocalDir As String
' Assign Folder where program resides to LocalDir
LocalDir = App.Path
' Append right backslash if last character is not "\"
If Right(LocalDir, 1) <> "\" Then
LocalDir = LocalDir & "\"

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

10

End If
' Load graphic "sad.bmp" from SubFolder "images" into Image1
Image1.Picture = LoadPicture(LocalDir & "images\sad.bmp")
End Sub

D nhin, nu ta mun load graphic lc run-time th phi cung cp graphic file


ring.

Control Shape
Control Shape cho php bn v nhng hnh n gin nh ng thng, hp,
vng trn trn form, lc thit k. Sau khi DoubleClick ln control Shape trong
Toolbox thm mt control Shape vo form, bn chn loi Shape ca n t
ca s Properties ri nm vo mt gc ca Shape trn form drag ln nh ty .
Mun sn bn trong mt Shape, bn chn mu t property FillColor. Property
FillColor cng ging nh BackColor ca cc controls khc, nhng n ch c hiu
lc khi bn cho property FillStyle mt tr s khc hn l 1- Transparent
(trong sut), th d nh 0- Solid (dy c).

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

11

Control Line
Tng t vi cc properties Fill ca Shape, i vi Line bn c cc properties
BorderColor, BorderStyle v BorderWidth. Border color ch nh mu ca
chnh ng thng, BorderStyle cho bn la ng lin tc hay gch chm,
v BorderWidth lm cho ng dy to hn. Cc properties ny cng p dng
cho chu vi (ng bao quanh) ca cc hnh ch nht, trn .v.v.

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

12

Dng Ha (Phn III)


Graphics Methods
Trong khi cc Graphical Controls nh Shape, Line cho ta v hnh lc thit k th
Graphics Methods cho ta v nhng th y lc run-time. Ta cng c th chm
tng m (pixel) hay copy c mt Picture t ch ny n ch khc.
Ch cn mt cht kinh nghim bn c th lm hot ha (animation) hay to
visual effects tuyt diu m khng cn phi ng n Windows API
(Application Programming Interface) dng Function BitBlt.

Method PaintPicture
Method PaintPicture cho php bn copy rt nhanh mt khi d kin ha,
ni nm na l mt khu vc trong mt hnh graphic trn form, PictureBox hay
Printer n mt ni khc. Th d bn copy mt hnh t ch ny n ch khc
trong form, hay t form/PictureBox ra Printer Object mt chc sau bn in n
ra.
Bn hy khi ng mt d n VB6 mi v DoubleClick ln PictureBox Icon trong
ToolBox t mt PictureBox ln form. t tn PictureBox y l picGraphic v
set property Visible ca n ra False ta khng thy n lc run-time.
By gi load mt hnh vo property Picture ca picGraphic bng cch Browse
mt Bitmap file t ca s Properties. y ta chn INTL_NO.BMP t folder
\Program Files\Microsoft Visual
Studio\Common\Graphics\Bitmaps\Assorted

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

13

Trong chng trnh ny ta mun h khi nt tri ca Mouse xung v di


chuyn Mouse cursor th khi cursor i n u, hnh INTL_NO c v n .
Ta s dng mt Flag nh du nt-tri-ca-Mouse-Down, t tn l
flgMouseDown. Khi nhn c Event MouseDown ta set flgMouseDown
thnh True, v khi nhn c Event MouseUp ta reset flgMouseDown thnh
False. Mi ln nhn c Event MouseMove th nu flgMouseDown l True ta s
PaintPicture INTL_NO.
xa background ca form, ta thm mt button tn CmdClearForm chy
graphic method Cls. Di y l lit k code mu:
' Flag that indicates that the Mouse's left button is depressed
Dim flgMouseDown As Boolean
Private Sub Form_Load()
' Initialise flgMouseDown to False
flgMouseDown = False
End Sub
Private Sub Form_MouseDown(Button As Integer, Shift As Integer, X As
Single, Y As Single)
' Set Flag flgMouseDown
flgMouseDown = True
End Sub
Private Sub Form_MouseMove(Button As Integer, Shift As Integer, X As

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

14

Single, Y As Single)
' Paint picGraphic if flgMouseDown is True
If flgMouseDown Then
' Paint full-size picGraphic at Mouse cursor location
PaintPicture picGraphic.Picture, X, Y, picGraphic.Width,
picGraphic.Height
End If
End Sub
Private Sub Form_MouseUp(Button As Integer, Shift As Integer, X As
Single, Y As Single)
' Reset Flag flgMouseDown
flgMouseDown = False
End Sub
Private Sub CmdClearForm_Click()
' Clear the form
Cls
End Sub

Lu l bn phi declare variable flgMouseDown bn ngoi cc Subs mi


Sub u thy v c th dng n. Mun bit thm chi tit v cch dng method
PaintPicture, trong VB6 IDE DoubleClick ln ch PaintPicture trong code editor
highlight ch y ri bm nt F1.

Method PSet
Ta dng method PSet (n t ch Point Set) v mt pixel ln form. Ta cn
cho bit PSet u v vi mu g, tc l ta cho n ta X,Y ca pixel v mt
mu tnh t function RGB.
http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

15

Di y l code v pixels mu ln form mt cch bt chng (randomly)


v v tr v mu sc khi user clicks ln form chnh:
Private Sub Form_Click()
Dim i As Integer
' Variables for pixel coordinates
Dim iXCoord As Integer
Dim iYCoord As Integer
' Variable for primary colours
Dim iRed As Integer
Dim iGreen As Integer
Dim iBlue As Integer
' Start the Random number generation
Randomize
' Plot 2000 dots randomly
For i = 1 To 2000
' get a random XCoord.
' Note that Rnd(1) returns a real number between 0 and 1, eg:
0.384
iXCoord = Int(Rnd(1) * ScaleWidth)
' get a random YCoord.
iYCoord = Int(Rnd(1) * ScaleHeight)
' Get a random number between 0 and 254 for each primary colour
iRed = Int(Rnd(1) * 255)
iGreen = Int(Rnd(1) * 255)
iBlue = Int(Rnd(1) * 255)
' Plot the pixel at iXCoord,iYCoord
PSet (iXCoord, iYCoord), RGB(iRed, iGreen, iBlue)
Next
MsgBox ("All done!")
End Sub

Trong th d trn ta dng method Randomize generate sn trong b nh


cc con s real bt chng t 0 n 0.999. Sau mi ln ta gi Function
Rnd(1) l n s tr v mt con s real ly bt chng t b s do method
Randomize generated. Do , Rnd(1) * ScaleWidth s cho ta mt con s real
c tr s t 0 n ScaleWidth. Mun i con s real ra Integer, ta dng
Function Int.
Khi khi ng chng trnh v Click ln form ta s c hnh ging nh di y:

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

16

Mch nc: xa mt m bn Pset li ti ch y mt m mi c cng mu


vi BackColor ca form.

Method Line
Method Line v mt ng thng t mt ta ny n mt ta khc
trong mu do ta ch nh. Vi hai methods PSet v Line ta c th lm c rt
nhiu chuyn. Th d mun cho mt vt di ng, ta xa vt y bng cch v li
n vi cng mu ca BackColor ca form, ri v vt y v tr mi. Mun v mt
a gic nh tam gic hay ch nht ta rp nhiu ng thng li vi nhau, u
ca mi ng thng l cui ca ng thng va mi c v trc. Mun sn
Shade bn trong mt hnh ch nht ta dng PSet..v.v.
C ba cch ch nh ta ca hai u ca mt ng thng ta mun v:
1. Cho bit ta ca u v cui ng thng:
th d: Line (50, 100)-(3000, 4000)
Khi ng ny c v xong th v tr ca graphic cursor c
ta l v tr ca cui ng, tc l CurrentX=3000 v
CurrentY=4000 trong trng hp ny.
2. Ch cho bit ta cui ng thng:
th d: Line -(3600, 4500), vbMagenta
Trong trng hp ny v tr ca graphic cursor (CurrentX,
CurrentY) c ly lm ta ca u ng thng khi v.
Tc l nu trc khi execute dng code ny CurrentX=3000
v CurrentY=4000 th dng code tng ng vi:
Line (3000,4000)-(3600,4500), vbMagenta

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

17

3. Dng ch Step ni s khc bit t CurrentX v CurrentY:


th d: Line Step(400, 600)-Step(800, -500), vbGreen
Nu trc khi execute dng code ny CurrentX=3600 v
CurrentY=4500 th dng code tng ng vi:
Line (4000,5100)-(4800,4600), vbGreen
Trong th d di y, mt hnh tam gic c v bng hai cch coding khc
nhau. Khi chy program th, bn hy ln lt click Triangle METHOD I v
Triangle METHOD II thy c hai cch v u y nh nhau, ch khc mu
thi.
Private Sub CmdTrianI_Click()
' Drawing a black triangle: METHOD I
Line (700, 500)-(2800, 2400)
Line (2800, 2400)-(1800, 900)
Line (1800, 900)-(700, 500)
End Sub
Private Sub CmdTrianII_Click()
' Drawing a red triangle: METHOD II
' Draw a red line from Location(700, 500) to Location (2800, 24000)
Line (700, 500)-(2800, 2400), vbRed
' Draw a red line from Location(2800,2400) to Location (1800,900)
Line -(1800, 900), vbRed
' Draw a red line from Location(1800,900) to Location (700,500)
Line -(700, 500), vbRed
End Sub

v mt hnh ch nht, cch tin nht l dng Step nh di y:


Private Sub Rectangle(ByVal X1 As Integer, ByVal Y1 As Integer, ByVal
X2 As Integer, ByVal Y2 As Integer)
' Draw a rectangle
Line (X1, Y1)-(X2, Y1)
Line -(X2, Y2)
Line -(X1, Y2)
Line -(X1, Y1)
End Sub

Ta cn c th v mt hnh ch nht vi bn gc trn nh sau:


Private Sub RoundCornerRectangle(ByVal X1 As Integer, ByVal Y1 As
Integer, ByVal X2 As Integer, ByVal Y2 As Integer)
Const Delta = 50
' Draw a rectangle with round corner
Line (X1 + Delta, Y1)-(X2 - Delta, Y1)
Line -Step(Delta, Delta)
Line -(X2, Y2 - Delta)

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3


Line
Line
Line
Line
Line
End Sub

18

-Step(-Delta, Delta)
-(X1 + Delta, Y2)
-Step(-Delta, -Delta)
-(X1, Y1 + Delta)
-Step(Delta, -Delta)

Ta cng c th sn Shade bn trong hnh ch nht bng cch dng method PSet
chm cc m cch nhau chng 50 pixels nh sau:
Private Sub Shade(ByVal X1 As Integer, ByVal Y1 As Integer, ByVal X2 As
Integer, ByVal Y2 As Integer)
' Shade a roundcorner rectangle by plotting dots using method Pset
Const Delta = 50
Dim i As Integer
Dim j As Integer
' Make sure that X1 is less than X2
' Swap values of X1, X2 if X1 > X2
If X2 < X1 Then
Temp = X1
X1 = X2
X2 = Temp
End If
' Make sure that Y1 is less than Y2
' Swap values of Y1, Y2 if Y1 > Y2
If Y2 < Y1 Then
Temp = Y1
Y1 = Y2
Y2 = Temp
End If
' Plotting dots inside the rectangle at 50 pixels apart
For i = X1 + Delta To X2 - Delta Step 50
For j = Y1 + Delta To Y2 - Delta Step 50
PSet (i, j)
Next
Next
End Sub

Mun Shade m hn, bn c th chm cc m gn nhau hn, th d cho cch


nhau 30 pixels thay v 50 pixels. C mt cch khc l tng tr s ca
DrawWidth, dy ca ng v hay m.
By gi phi hp cch v hnh ch nht vi method Shade ni trn v method
Print ta c th vit ch bn trong mt khung mu nht nh sau:
Private Sub CmdDrawFrame_Click()
Dim X1 As Integer
Dim Y1 As Integer
Dim X2 As Integer
Dim Y2 As Integer
' Initialise Coordinates of rectangle

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

19

X1 = 4200: Y1 = 1000
X2 = 6200: Y2 = 2000
' Draw a roundcorner rectangle
RoundCornerRectangle X1, Y1, X2, Y2
' Shade the rectangle
Shade X1, Y1, X2, Y2
' Position cursor to Print some text
CurrentX = X1 + 50
CurrentY = Y1 + 50
' Define Font Size
Font.Size = 18
' Print the text at cursor location
Print "Hello there!"
End Sub

Khi chy chng trnh ny v click tt c cc buttons trn form, bn s c hnh


di y:

Hy nh set property AutoDraw ca form ra True cc graphic chng trnh v


khng b mt khi user minimises form.
Bn cng c th dng nhng k thut ni trn vi Object Printer in cc mu
giy in chi tit.

Method Circle
Ta dng Method Circle v hnh trn, hnh bu dc v ng cung, vi bn
trong trng rng hay c sn y bng mt mu ta ch nh. Ta phi cho bit
ta ca tm im vng trn v bn knh ca n.

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

20

Bn hy khi ng mt d n VB6 mi, t ln form mt button vi tn


frmCircle v caption Circle & Lines. DoubleClick ln button y v vit code sau
y:
Private Sub CmdCircleLine_Click()
' Draw a circle centered at 2000,1500 with radius equal 800
Circle (2000, 1500), 800
' Draw a vertical line from center
Line (2000, 1500)-Step(0, 800)
' Draw a horizontal line from center
Line (2000, 1500)-Step(800, 0)
End Sub

By gi hy t ln form mt button khc tn CmdArc v caption Draw Arc.


Thay v v nguyn mt vng trn, ta s ch v mt hnh vng cung bng mu .
ch nh rng ta s v t v tr no trn vng trn n v tr no khc, th d
t 45 n 230, ta cn phi i degree ra n v Radian bng cch dng
Function Rads nh sau:
Private Function Rads(ByVal Degree As Single) As Single
' Convert Degrees to Radian
Const PI = 22 / 7
Rads = Degree / 180 * PI
End Function

Vng cung lun lun c v ngc chiu kim ng h. Di y l code v


mt ng vng cung mu bn knh 800, tm im (4000, 2000), t 45
n 230:
Private Sub CmdArc_Click()
Circle (4000, 2000), 800, vbRed, Rads(45), Rads(230)
End Sub

Ta c th cho sn bn trong cc hnh trn, hay Pie Slices (mt phn ca hnh
trn) bng cch set FillStyle bng 0 v ch nh mu FillColor. Mt Pie Slice l
mt vng cung ng knh bi hai ng thng bn knh hai u. Mun v mt
Pie Slice ta nh thm du tr ("-") trc hai tr s Radian, tc l dng Rads(45), -Rads(230) thay v Rads(45), Rads(230).
Di y l code v hai Pie Slices, c tm im lch nhau mt t, ng thi thm
ch thch 87.5% v 12.5%.
Private Sub CmdPie_Click()
FillStyle = 0 ' Fill inside any closed shaped
FillColor = vbYellow

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3


' Draw a Pie Slice from 90deg to 45deg
Circle (3000, 4000), 800, , -Rads(90),
' Position the graphic cursor to Print
CurrentX = 2800: CurrentY = 4400
Print "87.5%"
FillColor = vbBlue
' Draw a Pie Slice from 45deg to 90deg
Circle (3050, 3900), 800, , -Rads(45),
' Position the graphic cursor to Print
CurrentX = 3400: CurrentY = 3000
Print "12.5%"
FillStyle = 1 ' No fill
End Sub

21
in Yellow
-Rads(45)
some text

in Blue
-Rads(90)
some text

Cch dng cui cng ca method Circle l v mt hnh bu dc (Elllipse).


V hnh bu dc ging nh v mt hnh trn nhng ta cn cho thm mt
parameter gi l Aspect. Aspect l s lin h gia bn knh vertical v bn knh
horizontal. Th d nu Aspect=2 th chiu cao ca hnh bu dc gp i chiu
ngang, ngc li, nu Aspect=0.5 th chiu ngang s gp i chiu cao.
Di y l code ta dng v hai hnh bu dc cng c, mt ci mu tm nm
thng ng v mt ci mu xanh nm ngang.
Private Sub CmdEllipse_Click()
Circle (1400, 3000), 800, vbMagenta, , , 2
Circle (1400, 3000), 800, vbBlue, , , 0.5
End Sub

Nu bn khi ng chng trnh v click c bn buttons bn s thy hnh sau


y:

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

22

Property DrawMode
Thng thng khi ta v, tr s default ca property DrawMode l 13- Copy
Pen. C mt tr s DrawMode rt thch hp cho p dng hot ha l 7- Xor
Pen. Mun xa mt hnh va v xong ta ch cn v li hnh y trong DrawMode
Xor Pen, khng cn bit trc background nh th no, n s hin ra tr li.

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

23

C s d liu (Database)
Table, Record v Field
Ni n c s d liu, ta lp tc ngh n SQLServer, Access hay Oracle .v.v.,
nhng ni cha rt nhiu d liu ta c th lu tr hay ly chng ra mt cch
tin li v nhanh chng. Hu ht cc chng trnh ta vit u c truy cp c s
d liu, v ta dng n nh mt cng c lm vic vi rt nhiu d liu trong
khi tp trung vo vic lp trnh phn giao din vi ngi dng (users).
Do ta cn c mt kin thc cn bn v kin trc ca c s d liu hiu l
do to sao ta thit k hay truy cp n theo nhng cch nht nh.
Ta s dng Access Database biblio.mdb, nm C:\Program Files\Microsoft
Visual Studio\VB98\biblio.mdb minh ha cc nim cn bit v c s d
liu.
Trong database ny c 4 tables: Authors (tc gi), Publishers (nh xut
bn), Titles ( mc) v Title Author.

Table Authors cha nhiu records. Mi record trong table Authors cha 3
fields: Au_ID, Author v Year Born (nm sanh). Ta c th trnh by Table
Authors di dng mt spreadsheet nh sau:

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

24

V cng mt field ca cc records hin th trong cng mt ct ca spreadsheet,


nn ta cng ni n mt field nh mt column (ct). V v mi data record
chim mt row (hng) ca spreadsheet, nn c khi ta cng ni n mt record
nh mt row.
Tht tnh m ni, ta khng cn phi c mt computer lu tr hay lm vic vi
mt table nh Authors ny. Ta c th dng mt hp ct, trn mi ct ta ghi
cc chi tit Au_ID, Author v Year Born ca mt Author. Nh th mi tm ct
tng ng vi mt record v nguyn ci hp l tng ng vi Table
Authors.
Ta s sp cc ct trong hp theo th t ca s Au_ID c th truy cp record
nhanh chng khi bit Au_ID. Ch kh mt ni, nu mun bit c bao nhiu tc
gi, trong s 300 ct trong hp, gi hn 50 tui th phi mt vi pht mi c th
tr li c. Database trong computer nhanh hn mt h thng bng tay
(Manual) l ch .

Primary Key v Index


trnh s trng hp, thng thng c mt field ca record, th d nh Au_ID
trong Table Authors, c dnh ra cha mt tr s c o (unique). Tc l
trong Table Authors ch c mt record vi field Au_ID c tr s y m thi. Ta gi
n l Primary Key.

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

25

Khng phi lc no ta cng mun truy cp mt record Author da vo Au_ID.


Nhiu khi ta mun dng chnh tn ca Author truy cp, do ta cng cn
phi sort sn cc records theo th t alphabet. Ta cng c th hp nhiu fields
li sort cc records. Tht ra, chnh cc records khng cn phi c di i
nm ng v tr th t. Ta ch cn nh v tr ca n u trong table l ri.
Ci field hay tp hp ca nhiu fields (th d surname v firstname ) dng
vo vic sorting ny c gi l Index (ngn tay ch). Mt Table c th c mt
hay nhiu Index. Mi Index s l mt table nh ca nhng pointers, cha v tr
ca cc records trong Table Authors. N ging nh mc lc index cui mt
cun sch cha trang s ch ta n ng phn ta mun tm trong quyn sch.
Khi thit k mt Table ta ch nh Datatype ca mi field c th kim tra
data cho vo c hp l hay khng. Cc Datatypes thng dng l Number, String
( cha Text), Boolean (Yes/No), Currency ( cha tr s tin) v Date (
cha date/time). Datatype Number li gm c nhiu loi datatypes v con s
nh Integer, Long (integer chim 32 bits), Single, Double, .v.v.

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

26

Di y l Datatypes ca cc fields trong record Author:

C loi Datatype c bit tn l AutoNumber. Tht ra n l Long nhng tr s


c pht sinh t ng mi khi ta thm mt record mi vo Table. Ta khng lm
g hn l phi chp nhn con s y.

Relationship v Foreign Key


By gi, nu bn ang chy Microsoft Access quan st database biblio.mdb,
bn c th dng Menu Command Tools | Relationships nh sau xem s
lin h (relationships) gia cc tables.

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

27

Access s hin th giao thoi Relationships, trong mi table c cha tn cc


fields. Mi table li c mt hay hai si dy ni qua cc tables klhc. Mi si dy
l mt mi lin h (relationship), n ni mt field trong mt table vi mt field c
cng tn trong table kia.
Th d nh gia hai tables Publishers v Titles c mi lin h da trn field
PubID (Publisher IDentification - s l lch ca nh xut bn). Hn na, nu
bn s thy u dy pha table Publishers c con s 1, cn u dy bn
pha table Titles c du v cc (). Ta gi mi lin h (1- ) l one-to-many,
ni mt nh xut bn c th pht hnh nhiu mc sch/CD.

Tng t nh vy, trong mi lin h one-to-many gia table Authors v Title


Author, ta thy mt tc gi (bn u c con s 1) c th sng tc nhiu tc
phm c i din bi cc record Title Author.
Trong khi gia hai tables Titles v Title Author, ta c mt mi lin h one-toone, tc l tng ng vi mi record Title ch c mt record Title Author. Cu
hi t ra l cc mi lin h one-to-many c ci g quan trng.
Tng tng khi ta lm vic vi table Titles (tm gi l Tc phm), nhiu khi ta
mun bit chi tit ca nh xut bn ca tc phm y. Tht ra ta c th cha
chi tit ca nh xut bn ca mi tc phm ngay trong table Titles. Tuy nhin,
lm nh th c im bt li l records ca cc tc phm c cng nh xut bn
s cha nhng d liu ging nhau. Mi ln mun sa i chi tit ca mt nh
xut bn ta phi sa chng trong mi record Title thuc nh xut bn y. V
mun cha chi tit ca mi nh xut bn mt ch duy nht, trnh s lp li,
nn ta cha chng trong mt table ring, tc l table Publishers.
Nu gi s ta bt u thit k database vi Table Titles, ri quyt nh tch cc
chi tit v nh xut bn vo mt table mi, tn Publishers, th k thut y
http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

28

c gi l normalization. Ni mt cch khc, normalization l thit k cc


tables trong database lm sao mi loi mnh d kin (khng phi l Key) ch
xut hin mt ch.
Trong mi lin h one-to-many gia tables Publishers v Titles, field PubID l
Primary Key trong table Publishers. Trong table Titles, field PubID c gi l
Foreign Key, c ngha rng y l Primary Key ca mt table l (foreign). Hay
ni mt cch khc, trong khi lm vic vi table Titles, lc no cn chi tit mt
nh xut bn, ta s ly cha kha l (Foreign Key) dng lm Primary Key ca
Table Publishers truy cp record ta mun. l chnh Table Titles c
Primary Key ISBN ca n.

Relational Database
Mt database c nhiu tables v h tr cc lin h, nht l one-to-many, c
gi l Relational Database. Khi thit k mt database, ta s tm cch sp t
cc d liu t th gii tht bn ngoi vo trong cc tables. Ta s quyt nh
chn cc ct (columns/fields) no, chn Primary Key, Index v thit lp cc mi
lin h, tc l t cc Foreign Key u.

Cc li ch
Trong s cc li ch ca mt thit k Relational Database c:

Sa i d kin, cho vo records mi hay delete (gch b)


records c sn rt hiu qu (nhanh).
Truy cp d kin, lm bo co (Reports) cng rt hiu qu.
V d kin c sp t th t v c quy c nn ta c th
tin cy tnh tnh ca database (khng c ba trn, khi th th
ny, khi th th khc - git git).
V hu ht d kin nm trong database, thay v trong
chng trnh ng dng, nn database t c documentation
(ti liu ct ngha).
D sa i chnh cu trc ca cc tables.

Integrity Rules (cc quy lut lim chnh)


Integrity Rules c dng ni v nhng qui lut cn phi tun theo trong
khi lm vic vi database m bo l database cn tt. C hai loi quy lut:
lut tng qut (General Integrity Rules) v lut ring cho database (DatabaseSpecific Integrity Rules). Cc lut ring ny thng ty thuc vo cc quy lut v
mu dch (Business Rules).

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

29

General Integrity Rules


C hai quy lut lim chnh lin h hon ton vo database: Entity (bn th)
Integrity Rule v Referential (ch n) Integrity Rule.
Entity Integrity Rule ni rng Primary Key khng th thiu c, tc l
khng th c tr s NULL. Quy lut ny xc nhn l v mi Primary Key a n
mt row c o trong table, nn d nhin n phi c mt tr s ng hong.
Lu l Primary Key c th l mt Composite Key, tc l tp hp ca mt s
keys (columns/fields), nn nht nh khng c key no trong s cc columns l
NULL c.
Referential Integrity Rule ni rng database khng th cha mt Foreign Key
m khng c Primary Key tng ng ca n trong mt table khc. iu y hm
rng:

Ta khng th thm mt Row vo trong mt Table vi tr s


Foreign Key trong Row y khng tm thy trong danh sch
Primary Key ca table bn pha one (1) m n lin h.
Nu c thay i tr s ca Primary Key ca mt Row hay
delete mt Row trong table bn pha one (1) th ta khng
th cc records trong table bn pha many () cha
nhng rows tr thnh m ci (orphans).

Ni chung, c ba nhim (options) ta c th chn khi thay i tr s ca Primary


Key ca mt Row hay delete mt Row trong table bn pha one (1):
1. Disallow (khng cho lm): Hon ton khng cho php
chuyn ny xy ra.
2. Cascade (nh hng dy chuyn): Nu tr s Primary Key
b thay i th tr s Foreign Key tng ng trong cc
records ca table bn pha many () c thay i theo.
Nu Row cha Primary Key b deleted th cc records tng
ng trong table bn pha many () b deleted theo.
3. Nullify (cho thnh NULL): Nu Row cha Primary Key b
deleted th tr s Foreign Key tng ng trong cc records
ca table bn pha many () c i thnh NULL, hm
ng c i tm thm chi tit u c.

Database-Specific Integrity Rules


Nhng quy lut lim chnh no khc khng phi l Entity Integrity Rule hay
Referential Integrity Rule th c gi l Database-Specific Integrity Rules.
Nhng quy lut ny da vo chnh loi database v nht l ty thuc vo cc

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

30

quy lut v mu dch (Business Rules) ta dng cho database, th d nh mi


record v tin lng ca cng nhn phi c mt field S Thu (Tax Number) do
s Thu V pht hnh cho cng dn. Lu l cc quy lut ny cng quan trng
khng km cc quy lut tng qut v lim chnh. Nu ta khng p dng cc
Database-Specific Integrity Rules nghim chnh th database c th b h v
khng cn dng c.

Microsoft Access Database Management System (MSAccess


DBMS)
Microsoft Access Database Management System gm c Database Engine v
nhng cng c i chung cung cp cho users mt mi trng lm vic thn
thin vi database, nh Database Design (thit k cc tables v mi lin h),
Data entry v bo co (reports). Km theo vi Visual Basic 6.0 khi ta mua l mt
copy ca Database Engine ca MSAccess. Tn n l Jet Database Engine, ci
li ca MSAccess DBMS. Cc chng trnh VB6 c th truy cp database qua Jet
Database Engine.
Nu trn computer ca bn c ci sn MSAccess, th bn c th dng thit
k cc tables ca database hay cho data vo cc tables.

Properties Required v Allow Zero Length


Khi thit k mt table field, lu property Required v nht l property Allow
Zero Length ca Text. Nu property Required ca mt field l Yes th ta
khng th update (vit) mt record vi field y c tr s NULL. Nu mt Text
field c property Allow Zero Length l No th th ta khng th update mt
record khi field y cha mt empty string.

Khi ta to mt record ln u, nu khng cho tr s ca mt field, th field y c


tr s l NULL. Thng thng, Visual Basic 6.0 khng thch NULL value nn ta
http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

31

phi th mt field vi Function IsNULL() m bo n khng c tr s NULL


trc khi lm vic vi n. Nu IsNULL tr v tr s False th ta c th lm vic vi
field y. Nh l khi tr s NULL c dng trong mt expression, ngay c khi
chng trnh khng cho Error, kt qu cng l NULL.

Lm vic vi cc versions khc nhau


Nu my bn ang chy MSAccess2002 th bn c th lm vic vi Access
database file version 97, 2000 v 2002. Nu cn phi convert t version ny qua
version khc, bn c th dng Access DBMS Menu Command Tools | Database
Utilities | Convert Database | To Access 2002 File Format.... Nu mun
gi nguyn version, bn c th convert database qua File Format 2002 sa
i, ri sau convert tr li File Format c.

Access database file ln ln rt nhanh, v cc records b deleted vn cn nm


nguyn, nn mi tun bn nn nh nn n li b ht cc records b
deleted bng cch dng Access DBMS Menu Command Tools | Database
Utilities | Compact and Repair Database... hay dng function
DBEngine.CompactDatabase trong VB6.

Dng Query vit SQL


Mt cch truy cp database l dng ngn ng Structured Query Language
(SQL) theo chun do ISO/IEC pht hnh nm 1992, gi tt l SQL92. Tt c
mi database thng dng u h tr SQL, mc du nhiu khi chng cn cho
thm nhiu chc nng rt hay nhng khng nm trong chun. Cc lnh SQL
thng dng l SELECT, UPDATE, INSERT v DELETE. Ta c th dng phng
tin thit k Query ca MSAccess vit SQL. Sau khi thit k Query bng cch
drag drop cc fields, bn c th dng Menu Command View | View SQL nh
sau:

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

32

Tip theo y l SQL statement ca Query bn trn m bn c th copy paste


vo trong code VB6:

Dng Link Table lm vic trc tip vi database loi khc


Ta c th dng mt database loi khc, nh DBase, trc tip trong VB6 nh
dng mt Access database bnh thng. Mun thit lp mc ni y, bn dng
Menu Command File | Get External Data | Link Tables... ri chn loi
DBase v chnh file ca table m bn mun dng nht n vo Access
database ang m:

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

33

Database Server v mt s nim


D Jet Database Engine l mt relational database rt tt v hiu nng, n thuc
loi File Based database, tc l n th ng, khng chy mt mnh nhng
phi ty thuc vo chng trnh dng n. File Based database khng thch hp
vi nhng ng dng c nhiu ngi dng cng mt lc.
Trong khi , mt Database Server nh SQLServer chy ring phc v bt
c chng trnh khch (client) no cn. Database Server thich hp cho cc ng
dng c nhiu users v ch c mt mnh n chu trch nhim truy cp d liu cho
mi clients. N c th cha nhiu routines a phng, gi l Stored
Procedures, thc hin cc cng tc client yu cu rt hiu nng. Database
Server thng c cch i ph hu hiu khi c s c v phn cng nh a h
hay cp in. Ngoi ra, Database Server c sn cc phng tin v an ninh v
backup. N cng c thm cc chc nng dng cho mng.
Ngy nay ta thu thp d liu di nhiu hnh thc nh Email, Word documents,
Speadsheet. Khng nht thit d liu lun lun c cha di dng table ca

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

34

nhng records v khng nht thit d liu lun lun c lu tr trong mt


database ng hong. D vy, chng vn c xem nh database di mt mt
chng trnh ng dng. Do , ta dng t Data Store (Kho d liu) thay th
cho database ni n ni cha d liu. V i vi chng trnh tiu th d
liu, ta ni n Data Source (Ngun d liu) thay v database.
Khi lp trnh bng VB6 truy cp database, ta nhn databse mt cch tru
tng, tc l du n l Access, DBase, SQLServer hay Oracle ta cng xem nh
nhau. Nu c thay i loi database bn di, cch lp trnh ca ta cng khng
thay i bao nhiu.
Trong tng lai, mt XML file cng c th c xem nh mt database nho
nh. N c th ng mt mnh hay l mt table trch ra t mt database chnh
huy. XML l mt chun m ta c th dng import/export d liu vi tt c
mi loi database h tr XML. Ta c th trao i d liu trn mng Intenet di
dng XML. Ngoi ra, thay v lm vic trc tip vi mt database ln, ta c th
trch ra vi tables t database y thnh mt XML file. K ta ch lp trnh vi
XML file cho n khi kt thc s ha (merge/reconcile) XML file vi database ln.
Nu phn ln cc chng trnh p dng c thit k lm vic cch ny, th
trong tng lai ta khng cn mt Database Server tht mnh.

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

35

Dng Control Data


Control Data
T VB5, Visual Basic cho lp trnh vin mt control truy cp c s d liu, tn
n ch n s l Data. Nh ta bit, c mt c s d liu Microsoft gi km khi ta
mua VB6 - l Jet Database Engine. Jet Database Engine l ci "phng
my" ca chnh MS Access Database Management System.
Cho n thi VB5, Microsoft cho ta ba k thut chnh:

DAO (Data Acess Objects): DAO l k thut b truyn ca


Microsoft, ch dng vi Jet Database Engine. N rt d
dng, hiu nng v tin, nhng b gii hn trong phm vi
MS Access. Du vy, n rt thnh hnh v c li ch thc tin.
ODBC (Open Database Connectivity): ODBC c thit
k cho php users ni vi loi databases m ch dng
mt method duy nht. iu ny ct bt gnh nng cho lp
trnh vin, ch cn hc mt k thut lp trnh duy nht m
c th lm vic vi bt c loi database no. Nht l khi sau
ny nu cn phi thay i loi database, nh nng cp t
Access ln SQLServer chng hn, th s sa i v coding
rt t. Khi dng ODBC chung vi DAO, ta c th cho Access
Database ni vi cc databases khc. C mt bt li ca
ODBC l n rc ri.
RDO (Remote Data Object): Mt trong nhng l do chnh
RDO c thit k l gii quyt kh khn v s rc ri
ca ODBC. Cch lp trnh vi RDO n gin nh DAO,
nhng tht ra n dng ODBC nn cho php users ni vi
nhiu databases. Tuy nhin, RDO khng c thnh hnh
lm.

VB6 tip tc h tr cc k thut ni trn, v cho thm mt k thut truy cp


database mi, rt quan trng, l ADO (ActiveX Data Objects). Trong mt
bi ti ta s hc v ADO vi nhng u im ca n. Tuy nhin, v DAO rt n
gin v hiu nng nn ta vn c th tip tc dng n rt hu hiu trong hu ht
cc p dng. Do bi ny v bi k s tp trung vo nhng k thut lp trnh
ph bin vi DAO.

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

36

Cch dng gin tin ca control Data l t n ln mt Form ri lm vic vi


nhng Properties ca n. Bn hy bt u mt d n VB6 mi, cho n tn
DataControl bng cch click tn project trong Project Explorer bn phi ri edit
property Name trong Properties Window.
DoubleClick ln Icon ca Control Data trong Toolbox. Mt Control Data tn
Data1 s hin ra trn Form. Mun cho n nm bn di Form, ging nh mt
StatusBar, hy set property Align ca n trong Properties Window thnh 2 Align Bottom.
Click bn phi hng property DatabaseName, k click ln nt browse c
ba chm chn mt file Access dabase t giao thoi cho Data1. y ta chn
E:\Program Files\Microsoft Visual Studio\VB98\BIBLIO.MDB , trong
computer ca bn c th n nm trn disk C hay D.

Trong chng trnh ny ta mun lm vic vi table Titles ca database


BIBLIO.MDB, xem v edit cc records. property DefaultType ca
Data1 c tr s 2- UseJet, tc l dng k thut DAO, thay v dng k thut
ODBC.
Khi bn click ln property Recordsource ca Data1, ri click ln ci tam gic
nh bn phi, mt ComboBox s m ra cho ta thy danh sch cc tables trong
database. Bn hy chn Titles. property RecordsetType ca Data1 c
tr s l 0 - Table:

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

37

Ci t mi m ta s dng thng xuyn khi truy cp d liu trong VB6 l


Recordset (b records). Recordset l mt Set of records, n c th cha mt
s records hay khng c record no c. Mt record trong Recordset c th l
mt record ly t mt Table. Trong trng hp y c th ta ly v tt c records
trong table hay ch nhng records tha ng mt iu kin, th d nh ta ch
mun ly cc records ca nhng sch xut bn trc nm 1990 (Year Published
< 1990).
Mt Record trong Recordset cng c th l tp hp cc ct (columns) t hai (hay
ba) tables qua cc mi lin h one-to-one v one-to-many. Th d nh khi ly
cc records t table Titles, ta mun c thm chi tit tn cng ty (Company
Name) v in thoi (Telephone) ca nh xut bn (table Publishers) bng cch
dng Foreign Key PubID trong table Titles lm Primary Key trong table
Publishers ly cc chi tit y.
Trong trng hp y ta c th xem nh c mt virtual (o) table l tp hp
ca hai tables Titles v Publishers.
By gi bn hy t ln Form 4 labels vi captions: Title, Year Published,
ISBN v Publisher ID. K cho thm 4 textboxes tng ng v t tn
chng l txtTitle, txtYearPublished, txtISBN v txtPublisherID.
Chn textbox txtTitle, ri set property Datasource ca n trong Properties
Window thnh Data1. Khi click ln property Datafield ca txtTitle v m
ComboBox ra bn s thy lit k tn cc Fields trong table Titles. l v Data1
c coi nh trung gian ly table Titles t database. y ta s chn ct Title.
Lp li cng tc ny cho 3 textboxes kia, v chn cc ct Year Published (nm
xut bn), ISBN (s l lch trong th vin quc t), v PubID (s l lch nh xut
bn) lm Datafield cho chng.

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

38

Ti y, mc du cha vit mt hng code, ta c th chy chng trnh c


ri. N s hin th chi tit ca record u tin trong table Titles nh di y:

Bn c th bm cc nt di chuyn Navigator Buttons i n cc record


u (first), trc (previous), k (next) v cui (last). Mi ln bn di
chuyn n mt record mi l chi tit ca record y s hin th. Nu khng dng
cc Navigator Buttons, ta cng c th code lm cng tc tng ong bng
cch gi cc Recordset methods MoveFirst, MovePrevious, MoveNext v
MoveLast.
Khi record cui ca Recordset ang hin th, nu ta gi method MoveLast th
property EOF (End-Of-File) ca Recordset tr thnh True. Tng t nh vy,
khi record th nht ca Recordset ang hin th, nu ta gi method
MovePrevious th property BOF (Begin-Of-File) ca Recordset tr thnh True.

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

39

Nu mt Recordset khng c cha mt record no c th c hai properties EOF


v BOF u l True.
c tnh hin th d liu trong cc textboxex theo ng record hin thi
(current record) c gi l data binding hay data bound (buc vo d
liu) v control TextBox h tr chc nng ny c ni l Data Aware (bit b
con d liu).
Khi record u tin ang hin th, nu bn edit Year Published i t 1985
thnh 1983 ri click Navigator button Next hin th record th nh, k click
Navigator button Previous hin th li record u tin th bn s thy l field
Year Published ca record u tin tht s c thay i (updated) thnh
1983.
iu ny c ngha rng khi Data1 navigates t record ny n record khc th
nu record ny c s thay i v user edited, n lu tr s thay i trc
khi di chuyn. Cha chc l bn mun iu ny, do , nu bn khng mun
user tnh c edit mt record th bn c th set property Locked ca cc
textboxes y thnh True user khng th edit cc textboxes nh trong hnh
di y:

Ch nh v tr Database lc chy chng trnh


Cch ch nh tn DatabaseName trong giai on thit k (at design time) ta
dng trc y tuy tin li nhng hi nguy him, v khi ta ci chng trnh ny
ln computer ca khch, cha chc file database y nm trong mt folder c
cng tn. Th d trn computer mnh th database nm trong folder E:\Program
Files\Microsoft Visual Studio\VB98, nhng trn computer ca khch th database
nm trong folder C:\VB6\DataControl chng hn. Do , khi chng trnh khi
ng ta nn xc nh li v tr ca database. Gi d ta mun database trong

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

40

cng mt folder vi chng trnh ang chy, ta c th dng property Path ca


Application Object App nh sau:
Dim AppFolder As String
Private Sub Form_Load()
' Fetch Folder where this program EXE resides
AppFolder = App.Path
' make sure it ends with a back slash
If Right(AppFolder, 1) <> "\" Then AppFolder = AppFolder & "\"
' Assign Full path database filename to Data1
Data1.DatabaseName = AppFolder & "BIBLIO.MDB"
End Sub

Vi cch code ni trn ta s m bo chng trnh tm thy file database ng


ch, khng cn bit ngi ta ci chng trnh bn u trong hard disk ca
computer khch.
Nu bn ang hc VB6 t xa, khi np bi database cho gim th VB6 m bn
hardcode (vit cht cng) v tr ca file database trong lc thit k th gim th
(tutor) cng gp cng s kh khn ny v cha chc gim th s cha database
trong mt folder c cng tn nh trong harddisk ca bn.

Thm bt cc Records
Chng trnh trn dng cng tm c, nhng n khng cho ta phng tin
thm (add), bt (delete) cc records. By gi bn hy vo Form 5 buttons
tn: cmdEdit, cmdNew, cmdDelete, cmdUpdate v cmdCancel.
Mc du bn khng thy, nhng tht ra Control Data Data1 c mt property
Recordset v khi ta dng Navigator buttons l di chuyn t record ny n
record khc trong Recordset y. Ta c th ni n n bng Notation (cch vit)
Data1.Recordset, v mi ln mun ly Recordset mi nht t database ta
dng method Refresh nh Data1.Recordset.Refresh.
Lc chung trnh mi khi ng, user ang xem (browsing) cc records th hai
buttons Update v Cancel khng cn phi lm vic. Do ta s nhn tin Lock
(kha) cc textboxes v disable (lm cho bt lc) hai buttons ny v khng cn
dng chng.
Trong Sub SetControls di y, ta dng mt parameter gi l Editing vi tr
s False hay True ty theo user ang Browse hay Edit, ta gi l Browse mode
v Edit mode. Trong Edit mode, cc Textboxes c unlocked (m kha) v
cc nt cmdNew, cmdDelete v cmdEdit tr nn bt lc:

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

41

Sub SetControls(ByVal Editing As Boolean)


' Lock/Unlock textboxes
txtTitle.Locked = Not Editing
txtYearPublished.Locked = Not Editing
txtISBN.Locked = Not Editing
txtPublisherID.Locked = Not Editing
' Enable/Disable buttons
CmdUpdate.Enabled = Editing
CmdCancel.Enabled = Editing
CmdDelete.Enabled = Not Editing
cmdNew.Enabled = Not Editing
CmdEdit.Enabled = Not Editing
End Sub

Trong Browse mode, Form c dng nh sau:

Sub SetControls c gi trong Sub Form_Load khi chng trnh khi ng v


trong Sub CmdEdit khi user click nt Edit nh sau:
Private Sub Form_Load()
' Fetch Folder where this program EXE resides
AppFolder = App.Path
' make sure it ends with a back slash
If Right(AppFolder, 1) <> "\" Then AppFolder = AppFolder & "\"
' Assign Full path database filename to Data1
Data1.DatabaseName = AppFolder & "BIBLIO.MDB"
' Place controls in Browse Mode
SetControls (False)
End Sub
Private Sub CmdEdit_Click()
' Place controls in Edit Mode
SetControls (True)
End Sub

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

42

Khi ta Delete mt record trong recordset, v tr ca record hin ti (current


record) vn khng thay i. Do , sau khi delete mt record ta phi
MoveNext. Kh ni, nu ta va delete record cui ca Recordset th sau khi
MoveNext, property EOF ca Recordset s thnh True. Thnh ra ta phi kim
tra iu , nu ng vy th li phi MoveLast hin th record cui ca
Recordset nh trong code ca Sub cmdDelete_Click di y:
Private Sub CmdDelete_Click()
On Error GoTo DeleteErr
With Data1.Recordset
' Delete new record
.Delete
' Move to next record
.MoveNext
If .EOF Then .MoveLast
Exit Sub
End With
DeleteErr:
MsgBox Err.Description
Exit Sub
End Sub

Trong lc code, ta Update (cp nht ha) mt record trong Recordset bng
method Update. Nhng ta ch c th gi method Update ca mt Recordset khi
Recordset ang trong Edit hay AddNew mode. Ta t mt Recordset vo
Edit mode bng cch gi method Edit ca Recordset, th d nh
Data1.Recordset.Edit. Tng t nh vy, ta t mt Recordset vo AddNew
mode bng cch gi method AddNew ca Recordset, th d nh
Data1.Recordset.AddNew.
Private Sub cmdNew_Click()
' Place Recordset into Recordset AddNew mode
Data1.Recordset.AddNew
' Place controls in Edit Mode
SetControls (True)
End Sub

Sau khi Recordset gi method Update th Recordset y ra khi AddNew hay Edit
modes. Ta cng c th t thot ra khi AddNew hay Edit modes, hay ni cho
ng hn l hy b mi pending (ang ch i) Update bng cch gi method
CancelUpdate, th d nh Data1.Recordset.CancelUpdate.

Dng DataBound Combo


Trong chng trnh hin ti ta ch hin th l lch nh xut bn (PubID) ca Title,
ch khng c thm chi tit. Phi chi mc du chng trnh lu tr PubID,
nhng hin th c Company Name ca nh xut bn cho ta lm vic khi
phi nh cc con s th hay qu. Ta c th thc hin iu bng cch dng
http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

43

Control DBCombo (Data Bound Combo). Bn hy dng IDE Menu Command


Project | Components... chn Microsoft Data Bound List Controls 6.0
ri click Apply.

K , thm mt DBCombo tn DBCombo1 vo Form. V ta cn mt Recordset


khc cung cp Table Publisher cho DBCombo1, nn bn hy thm mt control
Data th nh tn Data2 vo Form. Cho Data2, hy set property DatabaseName
thnh E:\Program Files\Microsoft Visual Studio\VB98\BIBLIO.MDB v
property RecordSource thnh Publishers. khng cho ngi ta thy hnh
Data2 lc run-time, bn hy set property Visible n thnh False.

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

44

Ci mc ch ca chng ta khi dng DBCombo1 l hin th Company Name ca


nh xut bn, nhng ng sau lng th khng c g thay i, tc l ta vn lm
vic vi PubID cho cc record Title ca Data1. Khi user click ln DBCombo1
chn mt nh xut bn, th ta theo Company Name m cha PubID tng
ng trong record Title ca Data1. Do c nhiu th ta phi sp t cho
DBCombo1 nh sau:
Property

Value

Ch thch

RowSource

Data2

y l datasource ca chnh DBCombo1. N cung


cp table Publishers.

Listfield

Company
Name

Khi RowSource pha trn c chn ri, Combo


ca property Listfield ny s hin th cc fields ca
table Publishers. Company Name l field ca
RowSource m ta mun hin th trn DBCombo1.

DataSource

Data1

y l datasource ca record m ta mun. edit, tc


l record ca table Titles

Datafield

PubID

Field (ca record Title) s c thay i.

BoundColumn

PubID

Field trong RowSource (table Publishers) tng ng


vi item user chn trong DBCombo1 (Company
Name).

Khi trong Edit mode user chn mt Company Name khc trong DBCombo1 ri
click nt Update bn s thy Textbox txtPublisherID cng i theo v hin th
con s l lch PubID mi. Nu trc khi Update bn mun thy PubID mi hin
th trong Textbox txtPublisherID th bn c th dng Event Click ca DBCombo1
nh sau:
Private Sub DBCombo1_Click(Area As Integer)
' Display new PuBID
txtPublisherID.Text = DBCombo1.BoundText
End Sub

Property BoundText ca DBCombo1 l tr s ca BoundColumn m ta c th


truy cp (vit hay c) c. Th d nh bn mun mi khi thm mt record
Title mi th default PubID l 324, tc l Company Name= "GLOBAL
ENGINEERING". Bn c th assign tr s 324 vo property BoundText ca
DBCombo1 trong Sub cmdNew_Click nh sau:
Private Sub cmdNew_Click()
' Place Recordset into Recordset AddNew mode
Data1.Recordset.AddNew
' Default Publisher is "GLOBAL ENGINEERING", i.e. PubID=324

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3


DBCombo1.BoundText = 324
' Place controls in Edit Mode
SetControls (True)
End Sub

Trong bi ti ta s hc thm v cch coding dng Recordset trong k thut


DAO.

http://ebooks.vdcmedia.com

45

T HC VISUAL BASIC 6.0 - PHN 3

46

Lp trnh vi k thut DAO


Reference DAO
Trong bi ny ta s hc nhng cch lp trnh cn bn vi MS Access database
qua k thut DAO m khng cn dng n Control Data nh trong bi trc.
Ta s cn n vi Objects trong th vin DAO, do nu bn m mt d n VB6
mi th hy dng Menu Command Project | References... chn Microsoft
DAO 3.51 Object Library bng cch click ci checkbox bn tri nh trong hnh
di y. (Mt cch nh tn ca Object ny l nh cu "thng cha cua O
35 con d").

Sau trong code ca Form chnh ta s declare variable myDatabase cho mt


instance ca DAO database v variable myRS cho mt DAO recordset. y
ta ni r Database v Recordset l thuc loi DAO phn bit vi Database v
Recordset thuc loi ADO (ActiveX Data Object) sau ny. l Intellisense
gip ta trong lc vit code:

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

47

By gi bn hy t ln Form chnh, tn frmDAO, 4 labels vi captions: Title,


Year Published, ISBN v Publisher ID. K cho thm 4 textboxes tng
ng v t tn chng l txtTitle, txtYearPublished, txtISBN v
txtPublisherID.
iu ta mun lm l khi Form mi c loaded, n s ly v t database mt
Recordset cha tt c records trong table Titles theo th t v mu t
(alphabetical order) ca field Title v hin th record u tin.

Dng keyword SET


Chuyn trc ht l m mt Database Object da vo tn y (full path
name) ca Access database:
' Open main database
Set myDB = OpenDatabase(AppFolder & "BIBLIO.MDB")

ch Set trong cu code trn. l v myDB l mt Pointer n mt


Object. Mc du t ry v sau ta s dng myDB nh mt Database theo cch
ging nh bt c variable thuc data type no khc, nhng khi ch nh ln u
l n t u n th ta dng ch Set, ni rng tht ra myDB khng phi l
Object Database, nhng l Pointer n Object Database. im ny cng ni n
cng kh hiu.
i khi l VB6 runtime dynamically allocates (dnh ra cho khi cn) mt phn
trong b nh (memory) cha Object Database khi ta nhn c n t
execution ca Method OpenDatabase. Du v tr ch cha Object Database
trong b nh khng nht nh, nhng v ta nm ci cn ch n v tr y nn ta
vn c th lm vic vi n mt cch bnh thng. Ci cn y l value (tr s) ca
variable myDB. V value ny khng phi l Object, nhng n cha memory

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

48

address ch n (point to hay refer to) Object Database, nn ta gi n l


Pointer.
Lp trnh dng Pointer ni chung rt linh ng l hiu nng trong cc ngn ng
nh C, Pascal, C++ ,v.v.. Tuy nhin, lp trnh vin phi nh tr li Operating
System phn memory mnh dng khi khng cn cn n na Operating
System li allocate cho Object khc. Nu cng vic qun l dng li memory
khng n tha th c nhng mnh memory nm lang bang m Operating Sytem
khng bit. Ln ln Operating System s khng cn memory d na. Ta gi hin
tng y l memory leakage (r). Cc ngn ng sau ny nh Java, C# u
khng dng Pointer na. Visual Basic khng mun lp trnh vin dng Pointer.
Ch trong vi trng hp c bit VB6 mi l ra cho ta thy tht ra trong hu
trng VB6 Runtime dng Pointer, nh trong trng hp ny.
Tng t nh vy, v Recordset l mt Pointer n mt Object, ta cng dng
Set khi ch nh mt DAO Recordset ly v t Method OpenRecordset ca
database myDB.
'Open recordset
Set myRS = myDB.OpenRecordset("Select * from Titles ORDER BY Title")

Ci parameter loi String ta dng cho method OpenRecordset l mt Lnh


(Statement) SQL. N ch nh cho database ly tt c mi fields (columns)
(Select *) ca mi record t Table Titles (from Titles) lm mt Recordset v
sort cc records trong Recordset y theo alphabetical order ca field Title
(ORDER BY Title).
Nh l Recordset ny cng ging nh property Recordset ca mt Control
Data m ta dng trong bi trc. By gi c Recordset ri, ta c th hin th chi
tit ca record u tin nu Recordset y c t nht mt record. Ta kim tra iu
y da vo property RecordCount ca Recordset nh trong code di y:
Private Sub Form_Load()
' Fetch Folder where this program EXE resides
AppFolder = App.Path
' make sure it ends with a back slash
If Right(AppFolder, 1) <> "\" Then AppFolder = AppFolder & "\"
' Open main database
Set myDB = OpenDatabase(AppFolder & "BIBLIO.MDB")
'Open recordset
Set myRS = myDB.OpenRecordset("Select * from Titles ORDER BY Title")
' if Recordset is not empty then display the first record
If myRS.RecordCount > 0 Then
myRS.MoveFirst ' move to first record
Displayrecord ' display details of current record
End If
End Sub

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

49

Sau khi dng method MoveFirst ca Recordset position current record


Record u tin, ta hin th tr s cc fields ca record bng cch assign chng
vo cc textboxes ca Form nh sau:
Private Sub Displayrecord()
' Assign record fields to the appropriate textboxes
With myRS
' Assign field Title to textbox txtTitle
txtTitle.Text = .Fields("Title")
txtYearPublished.Text = .Fields("[Year Published]")
txtISBN.Text = .Fields("ISBN")
txtPublisherID.Text = .Fields("PubID")
End With
End Sub

v field Year Publshed gm c hai ch nn ta phi t tn ca field y


gia hai du ngoc vung ([]). trnh b phin phc nh trong trng hp
ny, khi bn t tn database field trong lc thit k mt table hy dn dnh cc
ch li vi nhau, ng ri ra. Th d nh dng YearPublished thay v
Year Published.

Cc nt di chuyn
Mun c cc nt Navigators tng ng vi ca mt Control Data, bn hy t
ln Form 4 buttons mang tn CmdFirst, CmdPrevious, CmNext v CmdLast
vi captions: <<, <, >, >>.
Code cho cc nt ny cng n gin, nhng ta phi coi chng khi user mun di
chuyn qu record cui cng hay record u tin. Ta phi kim tra xem EOF c
tr thnh True khi user click CmdNext, hay BOF c tr thnh True khi user click
CmdPrevious:
Private Sub CmdNext_Click()
myRS.MoveNext ' Move to next record
' Display record details if has not gone past the last record
If Not myRS.EOF Then
Displayrecord ' display details of current record
Else
myRS.MoveLast ' Move back to last record
End If
End Sub
Private Sub CmdPrevious_Click()
myRS.MovePrevious ' Move to previous record
' Display record details if has not gone past the first record
If Not myRS.BOF Then
Displayrecord ' display details of current record
Else
myRS.MoveFirst ' Move back to first record

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

50

End If
End Sub
Private Sub CmdFirst_Click()
myRS.MoveFirst ' Move back to first record
Displayrecord ' display details of current record
End Sub
Private Sub CmdLast_Click()
myRS.MoveLast ' Move back to last record
Displayrecord ' display details of current record
End Sub

Khi chy chng trnh bn s thy n hin th chi tit ca Record u tin khc
vi trong bi trc y v cc records c sorted:

Bn hy th dng cc Navigator buttons cy nh, l vn ca mnh xem chng


lm vic c ng khng.
Ti y, khng bit bn c l d user c v tnh sa i mt chi tit no
trong cc textboxes, khng c record no b cp nht ha trong database khi
user di chuyn t record ny n record khc. L do l cc Texboxes khng c
Data Bound vi cc Fields ca Recordset.

Thm bt cc Records
Ging nh chng trnh trong bi ri, ta s thm phng tin thm (add),
bt (delete) cc records. By gi bn hy vo Form 5 buttons tn: cmdEdit,
cmdNew, cmdDelete, cmdUpdate v cmdCancel.
Ch no trong chng trnh trc ta dng Data1.Recordset th by gi ta dng
myRS.

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

51

Ta s dng li Sub SetControls vi parameter Editing c tr s False hay True


ty theo user ang Browse hay Edit. Trong Browse mode, cc Textboxes b
Locked (kha) v cc nt cmdUpdate v cmdCancel tr nn bt lc. Trong
Edit mode, cc Textboxes c unlocked (m kha) v cc nt cmdNew,
cmdDelete v cmdEdit tr nn bt lc.
V y khng c Data Binding nn i cho n khi Update (cp nht ha) ta
mi t Recordset vo AddNew hay Edit mode. Do ta ch cn nh l khi
user edits l ang Edit mt record hin hu hay thm mt Record mi. Ta cha
tr s Boolean y trong variable AddNewRecord. Nu user sp thm mt record
mi th AddNewRecord = True, nu User sp Edit mt record hin hu th
AddNewRecord = False.
Ngoi ra, khi User sp thm mt record mi bng cch click nt New th ta phi
t clear (lm trng) ht cc textboxes bng cch assign Empty string vo text
property ca chng nh sau:
' If Editing existing record then AddNewRecord = False
' Else AddNewRecord = true
Dim AddNewRecord As Boolean
Private Sub ClearAllFields()
' Clear all the textboxes
txtTitle.Text = ""
txtYearPublished.Text = ""
txtISBN.Text = ""
txtPublisherID.Text = ""
End Sub
Private Sub cmdNew_Click()
' Remember that this is Adding a new record
AddNewRecord = True
' Clear all textboxes
ClearAllFields
' Place controls in Edit Mode
SetControls (True)
End Sub
Private Sub CmdEdit_Click()
' Place controls in Edit Mode
SetControls (True)
' Remember that this is Editing an existing record
AddNewRecord = False
End Sub

Nu user clicks Cancel trong khi ang edit cc textboxes, ta khng cn gi


method CancelUpdate v Recordset cha b t vo AddNew hay Edit mode.
y ta ch cn hin th li chi tit ca current record, tc l hy b nhng g user
ang nh vo:

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

52

Private Sub CmdCancel_Click()


' Cancel update
SetControls (False)
' Redisplay details or current record
Displayrecord
End Sub

Lc user clicks Update, bn c dp kim tra data xem c field no b b trng


(nht l Primary Key ISBN bt buc phi c tr s) hay c g khng valid bng
cch gi Function GoodData. Nu GoodData tr li mt tr s False th ta
khng xc tin vi vic Update. Nu GoodData tr v tr s True th ta t
Recordset vo AddNew hay Edit mode ty theo tr s ca Boolean variable
AddNewRecord.
Ging nh khi hin th chi tit ca mt Record ta phi assign tng Field vo
textbox, th by gi khi Update ta phi lm ngc li, tc l assign property Text
ca tng textbox vo Record Field tng ng. Sau cng ta gi method Update
ca recordset v cho cc controls tr li Browse mode:
Private Function GoodData() As Boolean
' Check Data here. If Invalid Data then GoodData = False
GoodData = True
End Function
Private Sub CmdUpdate_Click()
' Verify all data, if Bad then do not Update
If Not GoodData Then Exit Sub
' Assign record fields to the appropriate textboxes
With myRS
If AddNewRecord Then
.AddNew ' Place Recordset in AddNew Mode
Else
.Edit ' Place Recordset in Edit Mode
End If
' Assign text of txtTitle to field Title
.Fields("Title") = txtTitle.Text
.Fields("[Year Published]") = txtYearPublished.Text
.Fields("ISBN") = txtISBN.Text
.Fields("PubID") = txtPublisherID.Text
' Update data
.Update
End With
' Return controls to Browse Mode
SetControls (False)
End Sub

Cng v khng c Data Binding, nn khi User Delete mt record, sau khi di
chuyn qua record k tip ta phi t hin th chi tit ca record nh sau:
Private Sub CmdDelete_Click()
On Error GoTo DeleteErr
With myRS

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

53

' Delete new record


.Delete
' Move to next record
.MoveNext
If .EOF Then .MoveLast
' Display details of current record
Displayrecord
Exit Sub
End With
DeleteErr:
MsgBox Err.Description
Exit Sub
End Sub

Tm mt record
Tip theo y, ta mun lit k cc sch c tiu cha mt ch hay cu no ,
th d nh ch "Guide". K user c th chn mt sch bng cch select tiu
sch y v click nt Go. Chng trnh s locate (tm ra) record ca sch y v
hin th chi tit ca n.
By gi bn hy cho vo Form mt textbox tn txtSearch v mt Image tn
ImgSearch. K t mt frame tn fraSearch vo Form. ln frame ny
mt listbox tn List1 hin th tiu cc sch, v hai buttons tn CmdClose
v CmdGo, vi caption Close v Go. Sau khi select mt sch trong List1, user s
click nt Go hin th chi tit sch y. Nu i , user s click nt Close
lm bin mt frame fraSearch.
Bnh thng frame fraSearch ch hin ra khi cn, nn lc u hy set property
Visible ca n thnh False. Ta s cho ImgSearch hin th hnh mt ng dm nn
bn hy click vo bn phi property Picture trong Properties Window chn
Icon
BINOCULR.ICO
t
folder
E:\Program
Files\Microsoft
Visual
Studio\Common\Graphics\Icons\Misc:

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

54

Ci Primary Key ca table Titles l ISBN. Khi user select mt sch ta mun bit
ISBN ca sch y locate (nh ch) n trong Recordset myRS. Do trong
khi thm tiu ca mt sch vo List1, ta ng thi thm ISBN ca sch y
vo mt Listbox th hai tn List2. Ta ch s dng List2 sau hu trng, nn hy
set property Visible ca n thnh False. Di y l code load tiu sch v
ISBN vo cc Listboxes:
Private Sub ImgSearch_Click()
' Show Search Frame
fraSearch.Visible = True
Dim SrchRS As DAO.Recordset
Dim SQLCommand As String
' Define SQL statement
SQLCommand = "Select * from Titles where Title LIKE '" & "*" &
txtSearch & "*" & "' ORDER BY Title"
' Fetch all records having Title containing the text pattern given
by txtSearch
Set SrchRS = myDB.OpenRecordset(SQLCommand)
' If Recordset is not Empty then list the books' titles in List1
If SrchRS.RecordCount > 0 Then
List1.Clear ' Clear List1
' We use List2 to contain the Primary Key ISBN corresponding to
the books in List1
List2.Clear ' Clear List2
With SrchRS
' Iterate through the Recordset until EOF
Do While Not SrchRS.EOF
' Display Title in List1

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

55

List1.AddItem .Fields("Title")
' Store corresponding ISBN in List2
List2.AddItem .Fields("ISBN")
.MoveNext ' Move to next record in the Recordset
Loop
End With
End If
End Sub

Khi user Click ImgSearch vi text pattern l ch Guide, ta s thy hnh di


y:

Trong SELECT statement bn trn ta dng operator LIKE trn text pattern, ch
Guide, c wildcard character (*) hai bn. Wildcard character l ch c (hay
khng c) ch g cng c. Trong trng hp ny c ngha l h c ch Guide
trong tiu sch l c, khng cn bit n nm u. Ngoi ra s chn la
ny Khng c Case Sensitive, tc l ch guide, Guide hay GUIDE u c
c.
Khi user clicks nt Go, ta s dng method FindFirst ca Recordset myRS
nh ch ca record c tr s Primary Key l hng text trong List2 tng ng vi
tiu dc chn trong List1 nh sau:
Private Sub CmdGo_Click()
Dim SelectedISBN As String
Dim SelectedIndex As Integer
Dim Criteria As String
' Index of line selected by user in List1
SelectedIndex = List1.ListIndex
' Obtain corresponding ISBN in List2
SelectedISBN = List2.List(SelectedIndex)
' Define Search criteria - use single quotes for selected text
Criteria = "ISBN = '" & SelectedISBN & "'"
' Locate the record, it will become the current record

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

56

myRS.FindFirst Criteria
' Display details of current record
Displayrecord
' Make fraSearch disappeared
fraSearch.Visible = False
End Sub

Lu l trong string Criteria, v ISBN thuc loi text, ch khng phi l mt con
s, nn ta phi kp n gia hai du ngoc n.

Bookmark
Khi di chuyn t record ny n record khc trong Recordset, i khi ta mun
nh du v tr ca mt record c dp s tr li. Ta c th thc hin iu y
bng cch ghi nh Bookmark ca Recordset.
Th d khi user clicks nt Go, ta mun nh v tr ca record lc y sau ny
quay tr li khi User clicks nt Go Back. Bn hy thm vo Form mt button tn
CmdGoBack vi Caption Go Back. Ta s thm mt variable tn
LastBookmark loi data type Variant:
Dim LastBookMark As Variant

Lc u button CmdGoBack invisible, v ch tr nn visible sau khi user clicks nt


Go. Ta thm cc hng codes sau vo Sub CmdGo_Click() nh sau:
' Remember location of current record
LastBookMark = myRS.BookMark
CmdGoback.Visible = True

Di y l code quay tr li v tr current record trc y trong Recordset:


Private Sub CmdGoback_Click()
' Reposition record to last position
myRS.BookMark = LastBookMark
' Redisplay details or current record
Displayrecord
End Sub

LastModified
LastModified l vi tr ca record va mi c sa i hay thm vo trong
Recordset. th iu ny bn hy thm mt button invisible tn
CmdLastModified vi caption l Last Modified. Button ny ch hin ra sau khi
user clicks Update. Bt c lc no bn Click nt CmdLastModified, record mi
va c sa i hay thm vo s hin th:

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3


Private Sub CmdLastModified_Click()
' Reposition record to last position
myRS.BookMark = myRS.LastModified
' Redisplay details or current record
Displayrecord
End Sub

Di y l hnh ca Form lc ang c thit k:

http://ebooks.vdcmedia.com

57

T HC VISUAL BASIC 6.0 - PHN 3

58

Lp trnh vi ADO (phn I)


Control Data ADO
Visual Basic 6 cho ta s la chn v k thut khi lp trnh vi database, hoc l
dng DAO nh trong hai bi trc, hoc l dng ADO (ActiveX Data
Objects).
S khc bit chnh gia ADO v DAO l ADO cho php ta lm vic vi mi loi
ngun d kin (data sources), khng nht thit phi l Access database hay
ODBC. Ngun d kin c th l danh sch cc a ch Email, hay mt file text
string, trong mi hng l mt record gm nhng fields ngn cch bi cc du
phy (comma separated values).
Nu trong DAO ta dng thng tn ca MSAccess Database th trong ADO cho ta
ni vi (connect) mt database qua mt Connection bng cch ch nh mt
Connection String. Trong Connection String c Database Provider (th d
nh Jet, ISAM, Oracle, SQLServer..v.v.), tn Database, UserName/Password
logon mt database .v.v.. Sau ta c th ly v (extract) nhng
recordsets, v cp nht ha cc records bng cch dng nhng lnh SQL trn
cc tables hay dng nhng stored procedures bn trong database.
Bnh thng, khi ta mi khi ng mt project VB6 mi, Control Data ADO
khng c sn trong IDE. Mun c n, bn hy dng Menu Command Project |
Components..., ri chn Microsoft ADO Data Control 6.0 (OLEDB) t giao
din Components nh di y:

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

59

Bn hy bt u mt d n VB6 mi, cho n tn ADODataControl bng cch


click tn project trong Project Explorer bn phi ri edit property Name trong
Properties Window. Sa tn ca form chnh thnh frmADO, v nh cu ADO
DataControl Demo vo Caption ca n.
DoubleClick ln Icon ca Control Data ADO trong Toolbox. Mt Control Data ADO
tn Adodc1 s hin ra trn Form. Mun cho n nm bn di Form, ging nh
mt StatusBar, hy set property Align ca n trong Properties Window thnh
2 - vbAlignBottom.
Click bn phi hng property (Custom), k click ln nt browse c ba chm
giao thoi Property Pages hin ra. Trong giao thoi ny, trn Tab General
chn Radio (Option) Button Use Connection String ri click nt Build....

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

Trong giao thoi Data Link Properties, Tab Provider, chn Microsoft Jet
3.51 OLE DB Provider, ri click nt Next >> hay Tab Connection.

http://ebooks.vdcmedia.com

60

T HC VISUAL BASIC 6.0 - PHN 3

61

ch Select or enter a database name ta chn E:\Program


Files\Microsoft Visual Studio\VB98\BIBLIO.MDB, trong computer ca bn
c th file y nm trn disk C hay D. Sau , bn c th click nt Test
Connection pha di th xem connection c c thit lp tt khng.

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

62

Lp connection xong ri, ta ch nh mun ly g v lm Recordset bng cch


click property Recordsource ca Adodc1. Trong giao din Property Pages ca
n chn 2-adCmdTable lm Command Type, k m Combo box cho
Table or Stored Procedure Name chn table Titles.

Ty theo cch ta dng Recordset trong ADO, n c ba loi v c gi l


Cursor Type. Cursor chng qua l mt tn khc ca Recordset:

Static Cursor: Static Cursor cho bn mt static copy (bn


sao cng ngc) ca cc records. Trong lc bn dng Static
Cursor, nu c ai khc sa i hay thm, bt g vo
recordset bn s khng thy.
Keyset Cursor: Keysey Cursor hn Static Cursor ch
trong lc bn dng n, nu c ai sa i record no bn s

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

63

bit. Nu ai delete record no, bn s khng thy n na.


Tuy nhin bn s khng bit nu c ai thm mt record no
vo recordset.
Dynamic Cursor: Nh ch sng ng (dynamic) hm ,
trong lc bn ang dng mt Dynamic Cursor, nu c ai
khc sa i hay thm, bt g vo recordset bn s thy
ht.

Bn hy chn tr s 2-adOpenDynamic cho property Cursor Type ca Adodc1:

By gi bn hy t ln Form 4 labels vi captions: Title, Year Published,


ISBN v Publisher ID. K cho thm 4 textboxes tng ng v t tn
chng l txtTitle, txtYearPublished, txtISBN v txtPublisherID.
thc hin Data Binding, bn hy chn textbox txtYearPublished (nm xut
bn), ri set property Datasource ca n trong Properties Window thnh
Adodc1. Khi click ln property DataField ca txtYearPublished v m
ComboBox ra bn s thy lit k tn cc Fields trong table Titles. l v Adodc1
c coi nh trung gian ly table Titles t database. y ta s chn ct Year
Published.
Lp li cng tc ny cho 3 textboxes kia, v chn cc ct Title (Tiu ), ISBN
(s l lch trong th vin quc t), v PubID (s l lch nh xut bn) lm
DataField cho chng.

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

64

n y, mc du cha vit mt hng code no, bn c th chy chng trnh


v n s hin th nh di y:

Data Form Wizard


gip lp trnh vin thit k cc data forms nhanh hn, VB6 cho ta Data Form
Wizard generate (pht sinh) ra mt form c h tr Edit, Add v Delete
records.
By gi bn hy khi ng mt standard project VB6 mi, tn ADOClass v
copy MS Access file BIBLIO.MDB, tc l database, vo trong cng folder ca d
n mi ny.

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

65

Mun dng Data Form Wizard, trc ht ta phi thm n vo mi trng pht
trin (IDE) ca VB6. Bn hy dng IDE Menu Command Add-Ins | Add-In
Manager.... Chn VB6 Data Form Wizard trong giao thoi, ri click Checkbox
Loaded/Unloaded ch Loaded hin bn phi hng "VB6 Data Form Wizard"
nh trong hnh di y:

Nu bn mun mi ln khi ng VB6 IDE l c sn Data Form Wizard trong


menu Add-Ins th ngoi option Loaded, bn click thm check box Load on
Startup.
Mt Add-In l mt menu Item mi m ta c th thm vo mt chng trnh
ng dng c sn. Thng thng, ngi ta dng Add-Ins thm chc nng
cho mt chng trnh, lm nh l chng trnh c sn chc nng y t u.
Bn hy khi ng Data Form Wizard t IDE Menu Command mi Add-Ins |
Data Form Wizard...

Khi trang Data Form Wizard - Introduction hin ra, click Next

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

Trong trang k chn Access lm Database Type.

http://ebooks.vdcmedia.com

66

T HC VISUAL BASIC 6.0 - PHN 3

67

Trong trang Database, click Browse chn mt MS Access database file.


y ta chn file BIBLIO.MDB t chnh folder ca chng trnh ny. on click
Next.

Trong trang Form, ta chn Single Record cho Form Layout v Class cho
Binding Type. on click Next. Nu ta chn ADO Data Control th kt qu s
ging ging nh khi ta dng Control Data DAO nh trong mt bi trc.

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

68

Trong trang Record Source ta chn table Titles. Listbox ca Available Fields
s hin th cc fields ca table Titles. Sau khi chn mt field bng cch click ln
tn field y trong Listbox, nu bn click hnh tam gic ch qua phi th tn field
y s c di qua nm di cng trong Listbox Selected Fields bn phi.
Nu bn click hnh hai tam gic ch qua bn phi th tt c mi fields cn li bn
tri s c di qua bn phi. Bn cng c th sp t v tr ca cc selected
fields bng cch click ln tn field y ri click hnh mi tn ch ln hay xung
di chuyn field y ln hay xung trong danh sch cc fields.
Ngoi ra, bn hy chn Title lm Column to Sort By trong ci Combobox ca
n cc records trong Recordset c sp xp theo th t ABC (alphabetical
order) ca field Tiu (Title).

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

69

Trong trang Control Selection, ta s y nguyn c mi buttons. Bn hy


click Next.

Khi Data Form Wizard chm dt, n s generate form frmADODataForm. Bn


hy remove Form1 v dng Menu Command Project | ADODataControl
Properties... i Startup Object thnh frmADODataForm. Th l tm xong
chng trnh Edit cc records ca table Titles.

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

70

Chng ta hy quan st ci Form v phn code c Data Form Wizard


generated. Trong frmADODataForm, cc textboxes lm thnh mt array tn
txtFields. Mi textbox u c property DataField nh sn tn field ca table
Titles. Th d nh txtFields(2) c DataField l ISBN. Form chnh khng dng
Control Data ADO nhng dng mt Object ca class clsTitles.
Phn Initialisation ca class clsTitles l Open mt Connection v ly v mt
Dataset c tn DataMember l Primary nh sau:
Private Sub Class_Initialize()
Dim db As Connection
Set db = New Connection
db.CursorLocation = adUseClient
' Open connection
db.Open "PROVIDER=Microsoft.Jet.OLEDB.3.51;Data
Source=E:\Websites\Vovisoft\VisualBasic\ADOForm\BIBLIO.MDB;"
' Instantiate ADO recordset
Set adoPrimaryRS = New Recordset
' Retrieve data for Recordset
adoPrimaryRS.Open "select Title,[Year
Published],ISBN,Description,Notes,PubID from Titles Order by Title", _
db, adOpenStatic,
adLockOptimistic
' Define the only data member, named Primary
DataMembers.Add "Primary"
End Sub

V v tr ca database, nu bn khng mun n cht cng mt folder no th


dng App.Path xc nh mi lin h gia v tr ca database v folder ca
chnh chng trnh ang chy, th d nh:
db.Open "PROVIDER=Microsoft.Jet.OLEDB.3.51;Data Source=" & App.Path &
"\BIBLIO.MDB;"

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

71

Trong Sub Form_Load, ta c th dng For Each i qua ht cc textboxes


trong array txtFields. V property Datasource ca textbox l mt Object nn ta
dng keyword Set point n n Object PrimaryCLS. ng thi ta cng phi
ch nh tn ca DataMember ca mi textbox l Primary:
Private Sub Form_Load()
' Instantiate an Object of class clsTitles
Set PrimaryCLS = New clsTitles
Dim oText As TextBox
' Iterate through each textbox in the array txtFields
'Bind the text boxes to the data source, i.e. PrimaryCLS
For Each oText In Me.txtFields
oText.DataMember = "Primary"
' Use Set because property Datasource is an Object
Set oText.DataSource = PrimaryCLS
Next
End Sub

Khi s di chuyn t record ny n record khc chm dt, chnh Recordset c


raise Event MoveComplete. Event y c handled (gii quyt) trong class
clsTitles bng cch li raise Event MoveComplete n c handled trong
Form.
Mun handle Event trong clsTitles ta phi declare recordset adoPrimaryRS vi
WithEvents:
Dim WithEvents adoPrimaryRS As Recordset
Private Sub adoPrimaryRS_MoveComplete(ByVal adReason As
ADODB.EventReasonEnum, _
ByVal pError As ADODB.Error, adStatus As ADODB.EventStatusEnum,
ByVal pRecordset As ADODB.Recordset)
' Raise event to be handled by main form
RaiseEvent MoveComplete
End Sub

V trong Form ta cng phi declare (object clsTitles) PrimaryCLS vi WithEvents:


Private WithEvents PrimaryCLS As clsTitles

Trong Form, Event MoveComplete s lm hin th v tr tuyt i (Absolute


Position) ca record bng code di y:
Private Sub PrimaryCLS_MoveComplete()
'This will display the current record position for this recordset
lblStatus.Caption = "Record: " & CStr(PrimaryCLS.AbsolutePosition)
End Sub

http://ebooks.vdcmedia.com

T HC VISUAL BASIC 6.0 - PHN 3

72

Khi user clicks Refresh, cc textboxes s c hin th li vi chi tit mi nht


ca record t trong recordset, nh khi c ai khc sa i record. Method
Requery ca clsTitles li gi method Requery ca Recordset nh sau:
Private Sub cmdRefresh_Click()
'This is only needed for multi user applications
On Error GoTo RefreshErr
' fetch the latest copy of Recordset
PrimaryCLS.Requery
Exit Sub
RefreshErr:
MsgBox Err.Description
End Sub
'In Class clsTitles
Public Sub Requery()
' Fetch latest copy of record
adoPrimaryRS.Requery
DataMemberChanged "Primary"
End Sub

http://ebooks.vdcmedia.com