You are on page 1of 0

Cc bi tp Microsoft .

NET 1
MC LC
Bi 1 Microsoft .NET Framework................................................................................. 2
Bi 2 Visual Studio.NET ............................................................................................. 13
Bi 3 Nhng khc bit gia VB.NET vi VB6 ........................................................... 37
Bi 4 Nhng chc nng i Tng mi ca VB.NET (phn I).................................. 59
Bi 5 Nhng chc nng i Tng mi ca VB.NET (phn II) ................................ 68
Bi 6 Nhng chc nng i Tng mi ca VB.NET (phn III) ............................... 82
Bi 7 Nhng chc nng i Tng mi ca VB.NET (phn IV)............................... 95
Bi 8 Nhng chc nng mi trong giao din ca s ca VB.NET (phn I) .............. 112
Bi 9 Nhng chc nng mi trong giao din ca s ca VB.NET (phn II)............. 124
Bi 10 Nhng chc nng mi trong giao din ca s ca VB.NET (phn III) ......... 134
Bi 11 Nhng chc nng mi trong giao din ca s ca VB.NET (phn IV) ......... 144
Bi 12 Nhng chc nng mi trong giao din ca s ca VB.NET (phn V) .......... 161
Cc bi tp Microsoft .NET 2
Bi 1
Microsoft .NET Framework

Ci t Visual Studio.NET Beta 2
Visual Studio.NET nm trong 3 CDs, gm c 4 files:
EN_VS_NET_BETA2_WINCUP.exe
EN_VS_NET_BETA2_CD1.exe
EN_VS_NET_BETA2_CD2.exe
EN_VS_NET_BETA2_CD3.exe
Chy EN_VS_NET_BETA2_WINCUP.exe Unzip n vo mt folder
trong mt harddisk (eg: E:\CD\WINCUP).
Ln lt chy EN_VS_NET_BETA2_CD1.exe,
EN_VS_NET_BETA2_CD2.exe v EN_VS_NET_BETA2_CD3.exe
Unzip chng vo chung mt folder trong mt harddisk (eg: E:\CD ).
Vic Unzip files c th rt lu, bn phi kin nhn ch cho n khi n kt
thc. Nu khng, khi ci t c th b than phin l thiu files.
K , trc ht chy Setup.exe ca Windows Component Update nh
di y, click No khi Warning dialog hin ra:
Tip theo, chy Setup.exe ca Visual Studio.NET:
Bn nn c CPU Pentium III, 500MHz tr ln, vi 256 MB RAM v t
nht 10GB Harddisk. V OS bn nn dng Windows 2000 (Professional
Cc bi tp Microsoft .NET 3
hay Server) hay Windows XP. L do chnh l cc versions Windows ny
h tr Unicode v c Internet Information Server (IIS) h tr ASPX ta
dng cho ASP.NET.
M cc Samples ca QuickStart
Trc khi expand Samples ca Quickstart bn cn phi ci t IIS. Nu
cha lm vic y bn b CD ca Windows2000 hay WindowsXP vo
install IIS component.
QuickStart Samples ca .NET Framework cha cc gii thch cn bn v
nhiu th d. expand cc Samples doubleclick Webpage
Starthere.htm nh trong hnh di y:
Khi trang Web ca QuickStart hin ra, click QuickStart, tutorials and
samples ri sau theo ch dn tng bc.
Trang Framework SDK QuickStart Tutorials cho ta cc bi tp ca
ASP.NET, Windows Forms v How Do I...
Nh nguyn cc folders ca Unzipped files (E:\CD, E:\CD\WINCUP),
ng delete chng, v .NET s cn dng chng. Ngoi ra, nu sau ny
.NET b corrupted v conflict vi cc application software khc, bn c
th ci t .NET li.
Gii hn ca Software Tools hin gi
Cc bi tp Microsoft .NET 4
Architect ca application software hin gi c ni chung ba tng (three
tiers): tng giao din (Presentation Tier), tng gia (Middle Tier) v tng
d kin (Data Tier):
Presentation Tier: Trong desktop Client ta dng VB6 v ni vi middle
tier qua DCOM. Trong browser based Client ta dng Javascript hay Java
applet. T browser based Client ta dng http ni vi middle tier qua
IIS/ASP (c th dng COM y).
Middle Tier: Cha cc rules validate data trn client v cc business
rules khc. Ta dng VB6 y, nhng cch trin khai COM vi nhng
Object Oriented Programming concepts rc ri hn bnh thng. Ta phi
thit k sao cho cc components scale well (dng cho mi c). C khi
dng Microsoft Transaction Server trn Windows NT hay COM+
Services trn Windows 2000. Lp rp cc versions ca components l
mt thch thc ln.
Nhiu khi middle tier cn ni chuyn vi cc database qua HTTP, ADO
v CDO (Collaborative Data Objects), .v.v..
Data Tier: Thng l relational database nh Microsoft SQL Server hay
Oracle. Ngoi ra cn c Exchange hay cc database xa ca mainframe.
Do ta thy:
Desktop tools khng thch hp cho Distributed System
hay Internet
Phi dng nhiu th codes nh VB6 Code, VBScript,
JavaScript, Dynamic HTML, Cascading Style Sheet,
VC++, Stored Procedures (Transact-SQL trong
SQLServer hay PL-SQL trong Oracle).
Ty thuc qu nhiu vo central database: Ngay c ADO d l tin dng
cng i hi Client lun lun connect vi Server. iu ny khng thch
Cc bi tp Microsoft .NET 5
hp cho Internet applications, v bn cht ca Internet l stateless (khng
gi trng thi), mi ln cn lm vic mi connect li mt cht thi.
DLL "Hell": Cc ActiveX cn phi c registered
vi Windows Registry, ch c mt version c chp
nhn. Nu version mi nht ca mt DLL khng
compatible vi cc versions trc m applications
trn my ang cn th c rc ri.
Gii hn ca VB6
Thiu kh nng inheritance (tha k) v mt s Object
Oriented features khc.
Kh nng Error handling gii hn: On Error Goto ...,
On Error Resume Next
Cc bi tp Microsoft .NET 6
Nhiu khi cn phi gi Windows API lm nhng
vic VB6 khng h tr: vic ny khng t nhin v
i khi nguy him.
Khng c multi-threading: khng th on trc
response ca code chy trong cc windows ca cng
mt VB6 application. Ngay c gii quyt vn
multitasking bng Timers cng khng ng tin cy.
Khng d dng chung vi cc ngn ng khc nh
VC++.
Khng tin cho Web development: WebClass khng
thnh cng lm. t ai chu cho ta ci ActiveX trn my
ca h.
.NET Framework
.NET c developed t u nm 1998, lc u c tn l Next
Generation Windows Services (NGWS). N c thit k hon ton t
con s khng dng cho Internet. Vin tng ca Microsoft l xy dng
mt globally distributed system, dng XML (cha nhng databases t
hon) lm cht keo kt hp chc nng ca nhng computers khc nhau
trong cng mt t chc hay trn khp th gii.
Nhng computers ny c th l Servers, Desktop, Notebook hay Pocket
Computers, u c th chy cng mt software da trn mt platform duy
nht, c lp vi hardware v ngn ng lp trnh. l .NET
Framework. N s tr thnh mt phn ca MS Windows v s c port
qua cc platform khc, c th ngay c Unix.
Mc du hy cn l Beta, .NET Framework rt stable v Visual
Studio.NET rt t bugs, c th dng cho software development ngay t
by gi. Hin nay c mt s sch v lp trnh .NET do Wrox v
Oreilly xut bn.
Cc phn chnh ca Microsoft.NET Framework:
.NET application c chia ra lm hai loi: cho Internet gi l ASP.NET,
Cc bi tp Microsoft .NET 7
gm c Web Forms v Web Services v cho desktop gi l Windows
Forms.
Windows Forms ging nh Forms ca VB6. N h tr Unicode hon
ton, rt tin cho ch Vit v tht s Object Oriented.
Web Forms c nhng Server Controls lm vic ging nh cc Controls
trong Windows Forms, nht l c th dng codes x l Events y ht
nh ca Windows Forms.
im khc bit chnh gia ASP (Active Server Pages) v ASP.NET l
trong ASP.NET, phn i din visual components v code nm ring
nhau, khng ln xn nh trong ASP. Ngoi ra ASP.NET code hon ton
Object Oriented.
Web Services ging nh nhng Functions m ta c th gi dng t cc
URL trn Internet, th d nh Credit Card authorisation.
ADO.NET l mt loi cache database nho nh (gi l disconnected
database) thay th ADO. Thay v application connects vnh vin vi
database m qua ADO, application trong .NET lm vic vi portable
database ch cha mt hai tables, l copy t database m. Khi no cn,
portable database ny (ADO.NET) s c reconciled vi database m
update cc thay i. Hai tables trong ADO.NET c th c related nhau
trong Master/Details relationship. V ADO.NET c cha original data
ln data mi nht nn Rollback trong ADO.NET rt d dng v nh k.
XML c ym tr ti a. Nm pha sau ADO.NET l XML. XML c
th l Table of records trong ADO.NET hay Tree of nodes trong DOM
(Document Object Model).
IO c h tr bng ton b Stream k c Memory Stream v
StreamReader/StreamWriter. Thm vo l DataFormatting cho
Serialisation cha Object xung binary file hay text file.
TCP/IP v http l hai protocols thng dng nht trong .NET, nhng
chng lm vic pha sau sn khu gip ta gi mt remote procedure (nm
trn computer khc) d dng nh mt local procedure. K thut y gi l
Remoting.
Cc bi tp Microsoft .NET 8
Security h tr Cryptography, Permissions v Policy.
Diagnostics cho ta Debug v Trace.
Threading rt tin v n gin implement Lightweight Process. Vn
Timing trong .NET program rt linh ng, hiu qu v chnh xc.
Vic thit k Common Language Runtime nhm vo cc mc tiu chnh
sau y:
Vic trin khai n gin v nhanh hn: developers s
dnh th gi quyt nh rp nhng software
components no li vi nhau nhiu hn l lp trnh
tht s.
Cc cng tc thit yu ("plumbing") nh memory
management, process communication .v.v. c lo
liu t ng.
Cc cng c h tr rt y (no more API): .NET
Framework Base classes rt phong ph cho file,
network, serialisation, m ha, XML, database, v.v..
Ci t n gin v an ton (no more DLL "hell"): ch
cn xcopy files, ging nh thi vng son ca DOS. L
do l .NET application chy trn .NET framework,
mt khi ta ci .NET framework vo my ri th c
y mi .DLL cn thit. C l trong tng lai
Microsoft ci .NET framework chung vi Windows.
Dng cho t WindowsCE n Desktop, n Web
(scalability).
Cc bi tp Microsoft .NET 9
Metadata
Metadata l cc d kin ct ngha cho ta bit v d kin. Th d XML
Schema ca mt XML file l metadata ct ngha v data structure ca
data trong XML file. Chnh ci XML Schema cng l mt XML file. Cc
.NET application components, gi l Assembly, cha rt nhiu metadata
ct ngha v chnh n (self describing). Tm bit v mt .NET
application c th lm vic vi n th gi l Reflection.
H tr v phi hp mi ngn ng lp trnh
Common Language Runtime (CLR) l trung tm im ca .NET
Famework, n l hm my chy cc nng tnh ca .NET. Trong .NET,
mi ngn ng lp trnh u c compiled ra Microsoft Intermediate
Language (IL) ging ging nh byte code ca Java. Nh bt buc mi
ngn ng u phi dng cng cc loi data types (gi l Common Type
System) nn Common Language Runtime c th kim sot mi interface,
gi gia cc components v cho php cc ngn ng c th hp tc nhau
mt cch thng sut. Tc l trong .NET, VB.NET program c th inherit
C# program v ngc li mt cch hon ton t nhin.
iu ny chng nhng gip cc VC++ hay Java programmers bt u
Cc bi tp Microsoft .NET 10
dng C# mt cch d dng m cn lm cng mt d n vi VB.NET
programmers na.
Nu VC++ linh ng v hiu nng hn VB6, th C# chng khc g
VB.NET. Bn c th port C# code qua VB.NET code rt d dng. V
source code VC++ v Java gn gi C# hn VB6 vi VB.NET nn ngoi
i c nhiu C# code hn VB.NET. Do , mc du hai ngn ng
VB.NET v C# u ngang c nhau, nu dng C# bn c li im c
nhiu source code sn v nht l lu nay ngi ta vn mang n tng rng
VC++ hay Java programmers mi tht s l cc cao th lp trnh, v c
khuynh hng tr lng cc guru VC++/Java cao hn VB programmers.
Khi chy .NET application, n s c compiled bng mt JIT (Just-In-
Time) compiler rt hiu nng ra machine code chy. im ny gip
.NET application chy nhanh hn Java interpreted code trong Java
Virtual Machine. Just-In-Time cng c ngha l ch phn code no cn x
l trong lc y mi c compiled. IL code chy trong CLR uc ni l
managed code.
.NET code c th chy chung vi ActiveX, nhng code trong ActiveX
c gi l unmanaged code, tc l CLR khng chu trch nhim.
Ngoi vic allocation v management of memory, CLR cn gi cc
refrerence n objects v rc (handle garbage collection), tc l thu
li cc mnh vn memory khi chng khng cn dng na. Trc y, mi
khi mt DLL uc loaded vo memory, system s ghi nhn c bao nhiu
task dng n khi task cui cng chm dt th system unload DLL v
tr li phn memory n dng trc y system dng cho chuyn khc.
Ch nu allocate memory dng m khng nh dispose n th s b
memory leak (r ), ln ln ta dng ht memory, b bt buc phi reboot
Cc bi tp Microsoft .NET 11
OS. Nhng by gi .NET dng mt process c lp lm vic garbage
collection. Ci phn ng ph ca vic ny l khi ta Dispose mt
Object ri, ta vn khng bit chc chn chng no n mi tht s bin
mt. V garbage collector l mt low priority process lm vic trong
background, ch khi no system memory gn cn n mi nng cao
priority ln. D nhin, nu mun, ta c th i hi system Dispose mt
Object ngay lp tc.
Assembly
.NET application xy dng t cc assemblies. Mi assembly phi c mt
manifest. C th n nm ring trong mt file hay nm bn trong mt
module. Manifest cha nhng metadata sau y:
Tn v Version number ca assembly
Nhng assembly khc (k c version number ca
assembly) m assembly ny ty thuc vo chy
Cc bi tp Microsoft .NET 12
Types (classes v members) m assembly ny cho
xut khu
Assembly ny i hi iu kin an ninh no (security
permissions)
Manifest cho php ta dng hn mt version ca assembly (tng ng
vi DLL trc y) cng mt lc. T y khng cn register DLL na.
Thay vo , ta ch cn copy cc assembly vo mt subfolder /bin ca
chng trnh chnh.
Quyt nh ca bn
Sau khi bit qua v .NET, cu hi bn s t ra l bn c nn hc lp trnh
trn .NET hay khng. Ni chung, v lp trnh c nhiu tn gio nh
VC++/Java, VB6, Delphi ..v.v.. Bn c th chn gia C# v VB.NET.
i vi VB6 programmers, hc lp trnh VB.NET s mt mt thi gian,
nhng khng kh. Nn nh rng .NET khng phi ch cho ta cc ngn
ng lp trnh, m c mt h thng trin khai phn mm ch trng vo
mc tiu hn l cch thc. Cc li ch .NET cng hin cho bn cch thc
tin l:
K thut .NET s honh hnh trn giang h trong t 5
n 10 nm ti.
Tnh trung bnh, lp trnh trong .NET s tit kim th
gi cho bn t 25% n 50% so vi trc y. L do
l trong .NET bn s nghin cu dng component
no nhiu hn l tht s vit code. Hn na, hu nh
code no bn cn phi vit, bn s dng n li trong
tng lai. V bo tr .NET code th li cng khe hn
trc y, v chnh bn c vit bao nhiu code (c th
b bugs) u m bo tr.
Do , c l trong tng lai .NET programmers chng ta s ng n 10
gi sng mi thc, mt ngy ch cn lm vic vi ting, rnh rang lm
vn, cu c.
Trong bi ti ta s hc v Visual Studio.NET interface v bt u vit th
mt program Demo .
Cc bi tp Microsoft .NET 13
Bi 2
Visual Studio.NET
Visual Studio.NET
chy VisualStudio.NET bn cn phi Set Time ca Windows li trc
cui thng 7,2001, eg: 1-July-2001.
Visual Studio.NET Beta 2 hin nay c Service Pak 2, n cho php ta
dng Visual Studio.NET Beta 2 sau ngy 31-July-2001, tc l khng c
time-bomb. Nu VS.NET version ca bn b gii hn v thi gian ni
trn, t trong VS.NET bn c th download Service Pak 2 ci t bng
cch dng IDE Menu Command Help | Check for Updates.
C hai cch bt u mt project mi trong VS.NET. Hoc Click New
Project trong trang Web StartPage nh di y:
Hoc dng Menu command File | New | Project ging nh trong VB6
IDE:
Cc bi tp Microsoft .NET 14
Khi Add New Project, Name s l subfolder name ca New Project. Bn
c th chn VB.NET, C# hay VC++.NET project. Trong tng lai chng
ta s ch nhm vo VB.NET v C# thi. Ngoi ra SetUp and Deployment
by gi l mt loi project nm trong IDE ca Visual Studio.NET, ta
khng cn phi chy ring chng trnh Package and Deployment bn
ngoi VB6 IDE nh trc y.
Solution trong VS.NET c th cha hn mt Project v bao gm tt c
nhng files bn lit ra l cn thit cho Solution. Nu mt trong nhng
files y b thay i bn ngoi VS.NET, khi VS.NET khm ph ra n s
load vo trong VS.NET cho bn nu bn ng .
Cc bi tp Microsoft .NET 15
m mt Solution/Project c sn, bn c th click link ca tn project
trn trang StartPage, hay dng Menu command File | Open | Project ,
hay Menu Command File | Recent Projects.
Visual Studio.NET IDE
Cc bi tp Microsoft .NET 16
Giao din ca VS.NET c nhng c im ging nh Delphi v Visual
InterDev ch code c generated t ng, Windows nm chung thnh
Tab set hay float khp ni, v h tr Solution rt thch hp cho vic trin
khai ca c i.
Toolbox bn tri cha Controls cho Windows Forms, Web Forms,
General Components, Data Components, HTML tags, XML Schema
tools v.v... Khi mt Form ang hin th, click ln mt button trong
Toolbox chn Tool Set bn cn. Toolbox trng thi Fixed displayed
(nh trong hnh trn) khi cy ghim pha trn m xung. Bn c th click
cy ghim cho n nm ngang v vertical Toolbox tab hin ra bn tri. Lc
y, Toolbox trong trng thi Auto Hide (hin ra/rt vo) nh di y:
Cc bi tp Microsoft .NET 17
Bn c th gi hu ht cc Windows hin th bng cch dng Menu
commands View, View | Other Windows v Debug | Windows:
Cc Windows bn phi c th float, nm chng ln nhau thnh nhng
Tabs trong mt Window set hay nm cnh nhau vertically tiled. Nm
Tittle bar di nguyn mt Window set i. Nm Window Tab ca mt
Window set ko ch mt Window ra. Bn c th chng hai
Cc bi tp Microsoft .NET 18
Windows li vi nhau bng cch nm Tittle bar ca mt Window
chng ln mt Window khc. Th nhch i, nhch li, trc khi bung
Window ra lm quen vi kt qu.
Pha di c Task List Window bn gi s sch v din tin ca d
n v qun l c i. Khi bn dng menu command Build | Build
compile program, nu c errors chng s c hin th trong Task List
Window. Double click ln mt hng error mang cursor n ch gy ra
error y trong code window.
Trong hnh di y, ta c comment out hng Dim sw As
StreamWriter:
Ngoi ra, Debug by gi bn c Output Window in ra cc
messages m trong VB6 bn dng Immediate Window. Th d trong VB6
bn vit:
Debug.Print "Count=" & CStr(Count)
in ra trong Immediate Window, th trong VB.NET bn c th vit:
Console.WriteLine("Count= {0}", Count)
Cc bi tp Microsoft .NET 19
in ra trong Output Window.
D nhin bn vn c th tip tc dng Immediate Window trong cng tc
Debug nh trc y trong VB6.
Cha ht, VS.NET cn cho bn Command Window ta c th enter
nhng VS.NET commands manipulate IDE, x l macros, .v.v
hin th Window ny bn dng menu command View | Other
Windows | Command Window. tin hn, bn drag title bar ca n
chng ln tab bar ca Task List v Output windows.
Nu ta enter mt command nh:
File.AddNewProject
IDE s hin th Add New Project dialog.
VS.NET h tr Macro bn c th record v playback mt chui cng
tc.
Phng tin Integrated Debugging cho ta Debug Menu, Call Stack
Window, Breakpoints Window v Watch and Value Display
Windows.
Thng thng bn s Add Reference cc .NET components. Nhng bn
cng c th dng ActiveX (c sn trong VB6) trong .NET application
bng cch Add Reference COM (click Tab COM trn Add Reference
Dialog). .NET s gi ActiveX thnh mt NET component (click Yes tr
Cc bi tp Microsoft .NET 20
li cu hi "Would you like to have a wrapper generated for you?").
Ngoi ra dng Add Reference Projects refer n DLL ca cc User
developed DLL.
Demo Program
Trong chng trnh biu din ny, ta dng giao din hu nh hon ton
bng ch Vit. Ta c th nh ch Vit (Unicode) cho Title Bar, Menu,
TextBox, ListBox .v.v..
Nu bn cn mt key input software cho ch Vit h tr Unicode th
download VPS, Vietkey hay Unikey.
Cc documents nh Form, XML .v.v. trong .NET project u c Saved
vi UTF-8 encoding.
Cc bi tp Microsoft .NET 21
Trong program S th Saigon ny ta c hai Listboxes. Khi chy, bn c
th drag tn cc loi th t Listbox1 (bn tri) drop vo Listbox2 (bn
phi). Pha di l mt Label dng hin th ngy gi. C mt button
Lu tr danh sch ta save data trong Listbox2 vo file animal.txt
trong subFolder bin. Ngoi ra bn cng c th dng Main menu Item c
danh sch Load data t file animal.txt vo Listbox2.
Nhng components khng cn phi hin ra lc runtime nh Timer,
Menu, Tooltip .v.v. nm trong mt Component Tray (mm) ring. Mun
Edit MainMenu, click ln MainMenu1 icon ri nh trc tip vo
MainMenu. Thm cc menuitems mi bng cch nh thng vo cc ch
c ch Type Here. Lu cc Tabs bn trn Editing Area khi bn m
nhiu forms.
Cc bi tp Microsoft .NET 22

Edit MainMenu, insert mt Separator
Cc bi tp Microsoft .NET 23
Ch danh sch cc References c lit k trong Solution Explorer.
Edit Shortcut cho mt menu item.
Cc bi tp Microsoft .NET 24
Button by gi chng nhng c th cha hnh m cn cho bn chn v tr
ca hnh trong button bng ImageAlign na.
Bn c th Anchor mt Button n dnh vo mt gc ca form khi
form resizes th Button chy theo gc y ca form. y ta click hai
thanh Di v Phi cho chng tr nn mu en chn Anchor Bottom
v Right.
Cc bi tp Microsoft .NET 25
Trong lc thit k ta c th edit cc List items ca mt Listbox bng cch
m property Items Collection ra v Edit vo mt trang.
Walk Through Code
Trong .NET, cc classes c chia ra thnh nhiu nhm nh System.IO,
System.XML, System.Data, System.Drawing ..v.v..
Ngoi ra trong mi nhm li cn chia thnh nhng nhm con, chu nh
System.Windows.Forms, System.Windows.Collections,
System.Windows.Diagnostics, .v.v.. Mc du mt khi Project | Add
Reference cc .NET components y ta c th dng chng trong program
Cc bi tp Microsoft .NET 26
nhng vn phi bin mt tn di nh System.IO.StreamReader trnh
ln ln. c th vit tn class gn hn ta dng Imports nh Imports
System.IO, sau ta ch cn vit StreamReader l . Cng vic
Imports ny c gi l importing Namespace (ca System.IO).
Tng t nh th, c th tip tc dng cc Functions Left, Right, Mid
ca VB6 trong .NET ta c th thm cu Imports VB6 =
Microsoft.VisualBasic u chng trnh. Sau ta c th vit:
AppPath = VB6.Left(AppPath, Pos)
Nguyn program chng ta ti y l Public Class Form1. Form1 tha k
standard form class ca .NET Framework nn ta declare:
Inherits System.Windows.Forms.Form
Imports System.IO
Imports VB6 = Microsoft.VisualBasic
Public Class Form1
Inherits System.Windows.Forms.Form
Dim AppPath As String
Private Sub MenuItem4_Click(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles MenuItem4.Click
End ' Terminate the program
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
' Obtain the folder where this program EXE resides and initialise tooltip
Cc bi tp Microsoft .NET 27
Dim AppPath As String
Dim Pos As Integer
' Fetch full pathname of the EXE file
AppPath = System.Reflection.Assembly.GetExecutingAssembly.Location
' Locate the last slash in the pathname string
Pos = InStrRev(AppPath, "/")
' Extract the part up to the backslash
AppPath = VB6.Left(AppPath, Pos)
' Initialise the tooltip for Listbox1
ToolTip1.SetToolTip(ListBox1, "Xin nm ko tn mt con th qua Listbox bn phi")
End Sub
Hy xem cch vit mt Event Handler nh:
Private Sub MenuItem4_Click(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles MenuItem4.Click
Khc vi VB6, n c thm cc ch Handles MenuItem4.Click pha cui
ni handling event Click ca MenuItem4. Mi Event Handler u
c passed cho hai parameters: ByVal sender As System.Object v
ByVal e As System.EventArgs. Parameter th nht, sender, l Object ch
ng chuyn RaiseEvent, cn e l Event c cha nhiu d kin khc nhau
ty theo tnh hung. Khi edit code bn c th nh Intellisense ca IDE
gip cho bit parameter e cha nhng d kin g.
Trong .NET, vn handling event khng phi l mt iu b him nh
trong VB6. Khi mt control c th RaiseEvent th chng nhng mt, m
Cc bi tp Microsoft .NET 28
nhiu controls khc u c th ng k (Register) c Thng bo
(Notified) khi Event y xy ra.
Control RaiseEvent c gi l Publisher (Nh Xut Bn), cc controls
mun handle event c gi l Subcribers (nhng Ngi t Mua di
hn) . D nhin cch handle event ca mi control u khc nhau, du
rng c passed cho cng hai parameters. Cc EventHandlers ny c
gi l Delegates (nhng Nh i Din lnh trch nhim gii quyt mt s
c).
Do , ta c th dng vn vn mt EventHandler handle nhiu Event
khc nhau, xut pht t nhiu Objects. Ni cho n gin ra, sau khi ta
ng k mt hay nhiu Delegates (tc l EventHandler Subs), th khi
Event xy ra, cc EventHandler Subs y s c x l.
Nu bn vn cn thy kh hiu th hy c th d ny. Tng tng bn
lm bing nu n nn t nh hng giao cm mi ngy n tn nh. C
hai cch bn nhn "g-mn" cm:
1. Ngi giao cm s "g-mn" cm trc nh, cnh
bn hp th. Khi i lm v, bn s mang n v nh.
Trong trng hp ny bn x l cng vic khi no
tin, tc l lc v n nh. Cch ny c im bt li l
hm no bn i lm v tr th cm c th b thiu v
tri nng.
Bn a cha kha nh cho ngi giao cm gi. Khi giao cm, ngi y
s t ng m ca v nh "g-mn" thng vo trong t lnh. Trong
cch ny Event GiaoCm c handled bng EventHandler Sub
OpenDoorPutIntoFridge, do ngi giao cm x l, ch khng phi
chnh bn.
Nh th, l Subscriber (ngi n cm thng giao tn nh) bn register
EventHandler "Sub OpenDoorPutIntoFridge" vi ngi giao cm qua
Cc bi tp Microsoft .NET 29
vic a cha kha. Khi Event "GiaoCm" xy ra, ngi giao cm t
ng executes Sub OpenDoorPutIntoFridge. K thut giao AddressOf
Sub cho mt Object khc n execute khi cn cn c tn l CallBack.
Do , ngay c trong lc runtime (khng phi khi design), Register
EventHandler Sub MenuItem4_Click vi system handle Event Click
ca MenuItem4 ta c th execute code:
AddHandler MenuItem4.Click, AddressOf MenuItem4_Click
Lu cch ta dng control ToolTip1 register Tooltip Text vi
Listbox1. Ta c th dng ch mt control ToopTip1 register nhiu
Tooltip Texts vi nhng controls khc nhau nh TextBox, ComboBox
.v.v..
Bn c th thay th hng:
AppPath = VB6.Left(AppPath, Pos)
bng
AppPath = AppPath.SubString(0,Pos)
Trong VB6, Visual components ca mt form c cha di dng Text
din t cc controls rt d c ngay u form file, nhng n khng phi
l VB6 code.
Trong .NET, Visual components ca mt form c cha di dng code
tht s. Tc l, nu khng c VS.NET ta c th dng Notepad vit code
nh th v sau khi compile, n vn chy y ht nh trong trng hp ta
dng VS.NET. im ny ging nh trong Java, ta c th vit code bng
Notepad v dng Command line compile v link code file vi cc
components khc.
Th d nh khi ta vit mt VB.NET program n gin chy trn trong
DOS Console, ta c th compile n nh sau:
Cc bi tp Microsoft .NET 30
vbc /t:exe /r:system.dll mysource.vb
vbc l VisualBasic Compiler, /t: c ngha target tc l EXE chy
trong DOS console. /r: c ngha reference n DLL.
Nu mun chy trong Windows, ta dng:
vbc /t:winexe /r:system.dll /r:system.windows.forms.dll
mysource.vb
Bnh thng generated code c du trong Region khi chon ch,
hay khu gi chng ta sa i.
Click du + bn l tri m mt Region hay Sub/Function. Click du -
ng li.
i khi ta cng c th Edit generated code, nhng bn nh backup code
trc, ri form khng th hin th v b error, ch cho ta mt trang giy
trng, th ta cn c ng restore.
Cc bi tp Microsoft .NET 31
Mi class u c t nht mt Sub New, gi l Constructor (ging nh
Class_Initialize ca VB6 class) v Sub Dispose, gi l Destructor.
l hai Sub dng to ra v ph hy Object. V Form1 tha k t
Standard Form nn trong Sub New trc ht phi gi constructor
MyBase.New() ca cha n, v trong Sub Dispose sau ht phi gi
destructor MyBase.Dispose ca cha n.
M Class View Window
Bn c th Navigate trong Code qua Class View. DoubleClick ln tn ca
Object hay Sub/Function trong Class View mang cursor n code ca
n trong trang Edit.
Cc bi tp Microsoft .NET 32
Bi u di n DragDrop
Code ca DragDrop, lu ta phi vit thm Sub ListBox2_DragEnter
handle Event DragEnter.
Private Sub ListBox1_MouseDown(ByVal sender As Object, ByVal e As
System.Windows.Forms.MouseEventArgs) Handles
ListBox1.MouseDown
' Start the DragDrop process
Dim ItemIndex As Integer
Cc bi tp Microsoft .NET 33
' Identify the Listbox item that has mousedown using mouse coordinates
ItemIndex = ListBox1.IndexFromPoint(New System.Drawing.Point(e.X, e.Y))
' Start the DragDrop process passing along the ListboxItem as
ListBox1.Items(ItemIndex)
ListBox1.DoDragDrop(ListBox1.Items(ItemIndex),
DragDropEffects.Copy Or DragDropEffects.Move)
End Sub
Private Sub ListBox2_DragEnter(ByVal sender As Object, ByVal e As
System.Windows.Forms.DragEventArgs) Handles ListBox2.DragEnter
' Apply the copy effect
' AND remember to set the property Allow Drop of Listbox2 to TRUE
If (e.Data.GetDataPresent(DataFormats.Text)) Then
e.Effect = DragDropEffects.Copy
Else
e.Effect = DragDropEffects.None
End If
End Sub
Private Sub ListBox2_DragDrop(ByVal sender As Object, ByVal e As
System.Windows.Forms.DragEventArgs) Handles ListBox2.DragDrop
Dim LItem As String
Cc bi tp Microsoft .NET 34
' Obtain the Source ListItem String
LItem = e.Data.GetData(DataFormats.Text).ToString
' Add it to Listbox2
ListBox2.Items.Add(LItem)
' Remove the Item from Listbox1
ListBox1.Items.RemoveAt(ListBox1.FindString(LItem))
End Sub
Khi Load data vo Listbox ta dng StreamReader Open mt File as
Input.
Khi Save data ca Listbox vo mt Text file ta dng StreamWriter
Open mt File as Output (hay Append nu ta cho thm Option
Append=True):
Private Sub MenuItem2_Click(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles MenuItem2.Click
' Read the list of animals from a text file into Listbox2
Dim sr As StreamReader
Dim Pos As Integer
Dim TStr As String
ListBox2.Items.Clear() ' Clear Listbox2
' Use a StreamReader to open the UTF-8 file to read.
sr = New StreamReader(AppPath & "animals.txt")
' Read each line in the file.
' When the end of the file is reached, return the value "-1".
Dim x As String
Cc bi tp Microsoft .NET 35
While sr.Peek <> -1
x = sr.ReadLine() ' Read a line
ListBox2.Items.Add(x) ' Add it to Listbox2
End While
sr.Close() ' Close the file
End Sub
Private Sub SaveAnimalList()
' Save the content of Listbox2 into a UTF-8 Text file
Dim i As Integer
Dim sw As StreamWriter
' Open the file to write in UTF-8 mode, using a StreamWriter.
sw = New StreamWriter(AppPath & "Animals.txt")
' Write each line in the Listbox.
For i = 0 To ListBox2.Items.Count - 1
sw.WriteLine(ListBox2.Items(i))
Next
sw.Close() ' Close the file
End Sub
Ta hin th ngy v gi bng cch dng Timer1 v Shared Function DateTime.Now
formated bng hai Functions c sn ToLongDateString v ToLongTimeString.
Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles
Timer1.Tick
' Display Date and Time every half a second
Label3.Text = DateTime.Now.ToLongDateString & " " & DateTime.Now.ToLongTimeString
End Sub
Bn cng c th hin th ngy gi trong format khc bng cch vit:
Label3.Text = DateTime.Now.ToString("ddd dd/MM/yyyy hh:mm:ss")
c: WED 18/07/2001 09:16:42
Cc bi tp Microsoft .NET 36
trong Format string ta dng MM cho Month v mm cho Minute.
Cc bi tp Microsoft .NET 37
Bi 3
Nhng khc bit gia VB.NET vi VB6
V B.NET, cn gi l VB7, chng qua l C# vit theo li Visual Basic.
Nay VB7 hon ton l Object Oriented, tc l cho ta dng li (reuse)
classes/forms theo cch tha k tht thoi mi, nn n khc VB6 nhiu
lm.
Du vy, i vi VB6 programmers hc VB.NET khng kh. L do l
VB.NET khng cho thm nhiu t mi (reserved words). Ni chung cc
nim mi trong VB.NET u d lnh hi, nht l khi em ra p dng
cch thc t. l nh Microsoft vn gi nguyn tc du v lm sn
(ca VB6) nhng g rc ri pha sau sn khu, ta c th tp trung vo
vic tm kim mt gii php, thay v qu bn tm vo cch thc lm mt
vic g. Chnh nguyn tc y gip Microsoft chiu m c 3 triu
VB6 programmers trn khp th gii. VB.NET cng hin cho VB
programmers mt cng c rt hu hiu dng cho mi hon cnh, t
database, desktop, distributed, internet cho n real-time hay mobile
(pocket PC).
Nhng u im (features) ca VB.NET n t chc nng ca .NET
Framework. N mang n phng tin lp trnh cho mng cch Object
Oriented nh XML, Remoting, Streaming, Serialisation, Threading .v.v...
Nhng th ny tuy l nhng khng kh hc, ngc li s tit kim rt
nhiu th gi.
Mc du VB6 l mt ngn ng lp trnh trng thnh v hiu nng, chc
chn hy cn tn ti trong nhiu nm na, nhng hc thm VB.NET l
mt u t tng i t tn km v m bo hu li gp bao nhiu ln
trong hng thp nin ti.
Trong bi ny ta s bn v nhng im khc nhau gia VB6 v VB.NET
t quan im ngn ng lp trnh. Trong mt bi khc ta s bn v nhng
chc nng i tng (Object Oriented) ca VB.NET.
Namespaces
Namespaces l mt cch t tn gip sp t cc Classes ta dng
trong program mt cch th t hu d tm kim chng. Tt c code trong
Cc bi tp Microsoft .NET 38
.NET, vit bng VB.NET, C# hay ngn ng no khc, u c cha
trong mt namespace.
im ny cng p dng cho code trong .NET system class libraries.
Chng hn, cc classes ca WinForms u nm trong
System.Windows.Forms namespace. V cc classes dng cho collections
nh Queue, Stack, Hashtable .v.v.. u nm trong System.Collections
namespace.
Tt c code ta vit trong program ca mnh cng u nm trong cc
namespaces.
Trc y trong VB6, mi khi nhc n mt Class trong mt COM tn
CompName ta vit CompName.classname (cn gi l PROGID) , tc l
cng dng mt dng namespace.
Tuy nhin phng php ny c mt vi gii hn:
a ch ca class b buc cng vo component ang
cha n.
Nhng classes khng nm trong mt COM component
th khng c "namespace".
Cch gi tn PROGID ch c mt bc thi, khng c
bc con, bc chu.
Tn ca Component lun lun c hiu lc trn khp
c computer.
Namespaces trong .NET khc phc c mi gii hn ni trn trong
VB6.
Nhiu assemblies c th nm trong cng mt namespace, ngha l classes
tuyn b trong cc components khc nhau c th c chung mt
namespace. iu ny cng p dng xuyn qua cc ngn ng, gip cho
mt class vit trong VB.NET c th nm trong cng mt namespace vi
mt class vit trong C#, chng hn.
Hn na, trong mt assembly c th c nhiu namespaces, d rng thng
Cc bi tp Microsoft .NET 39
thng ta ch dng mt namespace duy nht cho tt c cc classes trong
y.
Nh l mt assembly trong .NET th i khi tng ng vi mt COM component.
Tt c code trong .NET u nm trong nhng assemblies.
By default, tn ca project c dng lm namespace. Nu bn right click
ln project name NETListbox trong Solution Explorer ca program
Demo, ri chn Properties trong popup menu, IDE s hin th Property
Pages dialog nh di y:
Bn thy Root namespace ca project l NETListbox. Bn c th thay
i tn namespace y nu bn mun.
Namespaces c th c phn chia th bc ging nh Folders trong mt
File Directory. N s gip user sp t cc classes theo ng nhm cho
trong sng v d c. Th d bn ang vit mt program cho mt hng
sn xut, bn s dng namespace NhSnXut root level. Bn trong
namespace y bn s to thm cc nhnh ca chng trnh nh:
NhSnXut.TnKho
NhSnXut.SnPhm
NhSnXut.KTon.ChiPh
NhSnXut.KTon.ThuNhp
Cc bi tp Microsoft .NET 40
Nh th ta nh ngha mt base namespace tn NhSnXut, vi
nhng namespaces con, chu bn trong, mi namespace c cha classes,
modules, enums, structures v cc namespaces khc.
Mi namespace cha nhng phn ca code thch hp cho n trong
program ni chung. Trong File Directory, ta c th c hai files d mang
cng tn nhng nm trong hai folders khc nhau. Ging nh vy, trong
.NET ta c th c hai classes c cng mt tn nhng nm trong hai
namespaces khc nhau. l v khi ta vit tn ca mt class vi c
namespace ca n th c th phn bit vi mt class khc vi cng tn.
Local v Global Namespaces
Khc vi COM components vi "namespace" ca chng p dng cho
khp c computer, namespaces ca .NET thng thng l Local, ch c
application program ca n thy m thi. .NET cng h tr Global
namespace, nhng phi c k tn (digitally signed) v ng k vi
.NET runtime cha n trong global assembly cache.
Cng vic lm mt namespace Global rc ri nh th gim thiu
trng hp ta tr v tnh trng DLL hell trc y.
Dng Namespaces
Ta c th dng namespaces bng cch ni thng ra (explicitly) vi
nguyn tn (Direct Addressing) hay hm (implicitly) vi Import
keyword. Nhng iu tin quyt l ta phi reference ci assembly cha
namespace m ta mun dng. Ta thc hin vic y vi Menu command
Project | Add References. Khi Add References dialog hin ra, chn Tab
.NET cho standard .NET components hay Tab Projects cho DLL ca
mt .NET project khc , highlight DLL bn mun ri click Select button,
on click OK.
Cc bi tp Microsoft .NET 41
Chng hn ta mun read v write t stdio (ci console input/output
stream). Ci namespace ta cn s l System.Console. Trong cch Direct
Addressing ta s code nh sau vit hng ch "Cho th gii":
System.Console.WriteLine ("Hello world!")
Nu ta dng Import keyword bng cch nht vo cu Imports
System.Console u code module, ta c th code gn hn:
WriteLine ("Hello world!")
Di y l mt s namespaces thng dng:
Namespace Chc nng Classes in hnh
System.IO
c/Vit files v cc data
streams khc
FileStream, Path, StreamReader,
StreamWriter
System.Drawing ha
Bitmap, Brush, Pen Color, Font,
Graphics
System.Data Qun l data
DataSet, DataTable, DataRow,
SQLConnection, ADOConnection
Cc bi tp Microsoft .NET 42
System.Collection
To v qun l cc loi
collections
ArrayList, BitArray, Queue, Stack,
HashTable
System.Math Tnh ton Sqrt, Cos, Log, Min
System.Diagnostics Debug Debug, Trace
System.XML
Lm vic vi XML,
Document Object Model
XMLDocument, XMLElement,
XMLReader, XMLWriter
System.Security
Cho php kim sot an
ninh
Cryptography, Permission, Policy
Aliasing Namespaces (dng b danh)
Khi hai namespaces trng tn, ta phi dng nguyn tn (k c gc tch)
phn bit chng. in hnh l khi ta dng nhng namespaces lin h n
VB6 nh Microsoft.Visualbasic. Thay v code:
Microsoft.Visualbasic.Left ( InputString,6)
ta tuyn b:
Imports VB6= Microsoft.Visualbasic
Sau ta c th code:
VB6.Left ( InputString,6)
Dng Namespaces keyword
Trong th d v program c Root Namespace l NhSnXut nh ni trn,
nu ta mun t ra mt namespace con l TnKho, ta phi dng
NameSpace keyword trong code nh sau:
' Root Namespace l NhSnXut
Namespace TnKho
Class PhngLnh
' Code cho Phng Lnh
End Class
End Namespace
Cc bi tp Microsoft .NET 43
By gi mun ni n class PhngLnh bn trong namespace TnKho ta
s code nh sau:
NhSnXut.TnKho.PhngLnh
Thay i trong Data Types
Tt c u l Object
Mt thay i ln cho Data Type ca VB.NET, l nhng variables dng
Data Type a phng nh Integer, Single, Boolean,.v.v.. u l nhng
Objects. Chng u c derived (xut pht) t Class cn bn nht tn
Object trong VB.NET. Nu bn th dng Intellisense xem c bao
nhiu Functions/Properties mt Object loi Integer c, bn s thy nh
di y:
Trong .NET, Integer c bn loi: Byte (8 bits, khng c du, tc l t 0
n 255), Short (16 bits, c du cng tr, tc l t -32768 n 32767),
Integer (32 bits, c du) v Long (64 bits, c du). Nh vy Integer by
gi tng ng vi Long trong VB6, v Long by gi ln gp i trong
VB6.
Floating-Point Division (Chia s ni)
Vic chia s ni (Single, Double) trong VB.NET c lm theo ng tiu
chun ca IEEE. Do nu ta vit code nh sau:
Dim dValueA As Double
Dim dValueB As Double
dValueA = 1
dValueB = 0
Cc bi tp Microsoft .NET 44
Console.WriteLine(dValueA / dValueB)
Trong VB6 ta bit mnh s gp Division by Zero error, nhng y
program s vit trong Output Window ch Infinity (v cc). Tng t
nh vy, nu ta vit code:
Dim dValueA As Double
Dim dValueB As Double
dValueA = 0
dValueB = 0
Console.WriteLine(dValueA / dValueB)
Kt qu s l ch NaN (Not a Number) hin th trong Output Window.
Thay th Currency bng Decimal
VB.NET dng Decimal data type vi 128 bits thay th Currency data
type trong VB6. N c th biu din mt s ti 28 digits nm bn phi
du chm cho tht chnh xc. H cng nhiu digits nm bn phi du
chm th tm tr s ca Decimal cng nh hn.
Char Type
VB.NET c c Byte ln Char data type. Byte c dng cho mt s nh
0-255, c th cha mt ASCII character trong dng con s.
Char c dng cha mt Unicode (16 bit) character. Char l mt
character ca String.
String Type
Nhn lt qua, String trong VB.NET khng c v khc VB6 bao nhiu.
Nhng tr khi ta mun tip tc dng cc Functions nh InStr, Left, Mid
and Right trong VB6, ta nn xem String l mt object v dng nhng
Properties/Functions ca n trong VB.NET cho tin hn. Sau ny ta s
hc thm v String ca VB.NET trong mt bi ring.
nim fixed-length (c chiu di nht nh) String trong VB6 khng cn
dng na. Do ta khng th declare:
Cc bi tp Microsoft .NET 45
Dim myString As String * 25
Object thay th Variant
Mt trong nhng data types linh ng, hiu nng v nguy him trong
VB6 l Variant. Mt variable thuc data type Variant c th cha gn
nh th g cng c (tr fixed-length string), n t ng thch nghi bn
trong cha tr s mi. Ci gi phi tr cho s linh ng y l program
chy chm v d c bugs to ra bi s bin i t data loi ny qua loi
khc khng theo d tnh ca ta.
VB.NET thay th Variant bng Object. V trn phng din k thut tt
c data types trong .NET u l Object nn, ging nh Variant, Object c
th cha th.
Ni chung, du Object ging nh Variant, nhng trong .NET ta phi ni
r ra (explicitly) mnh mun lm g. Ta th xem mt th d code trong
VB6 nh sau:
Private Sub Button1_Click()
Dim X1 As Variant
Dim X2 As Variant
X1 = "24.7"
X2 = 5
Debug.Print X1 + X2 ' Cng hai s vi operator +
Debug.Print X1 & X2 ' Ghp hai strings li vi operator &
End Sub
Kt qu hin th trong Immediate Window l :
29.7
24.75
Trong VB.NET, ta phi code cho r rng hn nh sau c cng kt qu
nh trn hin th trong Output Window:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
Button1.Click
Cc bi tp Microsoft .NET 46
Dim X1 As Object
Dim X2 As Object
X1 = "24.7"
X2 = 5
Console.WriteLine(CSng(X1) + CInt(X2))
Console.WriteLine(CStr(X1) & CStr(X2))
End Sub
CType Statement
Trong VB.NET c Option Strict by default. N bt ta phi thn trng
trong cch dng data types. V Object c th cha bt c th g, khi ta
mun dng n nh mt loi data type hay class no, ta phi i Object ra
th y bng CType, th d:
Class Product
Public Description As String
End Class
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
Button1.Click
Dim X As Object
X = New Product()
' Treat X like an actual product
CType(X, Product).Description = "Soft Drink"
Console.WriteLine(CType(X, Product).Description)
End Sub
Mc d X c instantiated nh mt Product, n vn c xem nh mt
Object variable. Do mi khi mun dng n nh mt Product ta phi
nh n CType. T chuyn mn trong programming gi l Type
Casting.
Thay i trong cch tuyn b Variables
Tuyn b nhiu Variables
Cc bi tp Microsoft .NET 47
Trong VB6 ta c th Declare nhiu variables trn cng mt hng nh:
Dim i, j, k As Integer
Kt qu l ch c k l Integer, cn i v j l Variant (c th l iu bn
khng ng). Trong VB.NET th c ba i,j v k u l Integer, v nh th
hp l hn.
Tuyn b tr s khi u
Trong VB6, sau khi declare variable ta thng cho n mt tr s khi u
nh:
Dim X As Integer
X = 12
By gi trong VB.NET ta c th gp chung hai statements trn li nh
sau:
Dim X As Integer = 12
Tuyn b Constants
Khi tuyn b Constants trong VB.NET ta phi khai r Data type ca n l
String, Integer, Boolean ..v.v.:
Public Const myConstantString As String = "happy"
Public Const maxStudent As Integer = 30
Dim As New
Trong VB6 ta c khuyn khng nn code:
Dim X As New Customer
v VB6 khng instantiate mt Object Customer cho n khi X c dng
n - chuyn ny rt nguy him v c th to ra bug m ta khng ng.
Trong VB.NET ta c th yn tm code:
Dim X As New Customer()
v statement ni trn lp tc to ra mt Object Customer.
Tuyn b Variable trong Scope ca Block
Cc bi tp Microsoft .NET 48
Trong th d di y, variable X c declared trong mt IF
..THEN...END IF block. Khi execution ra khi IF block y, X s b hy
dit.
Do , VB.NET s than phin l X undefined v n khng thy X bn
ngoi IF block. Lut ny cng p dng cho nhng Blocks khc nh
DO...LOOP, WHILE...END WHILE, FOR...NEXT, .v.v..
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
Button1.Click
Dim A As Integer = 5
Dim B As Integer = 5
If A = B Then
Dim X As Integer ' X is declared in this IF block
X = 12
End If
A = X ' X has been destroyed, so it is undefined here
End Sub
C l bn hi Declare Variable trong FOR...LOOP c li g, ti sao ta
khng Declare mt ln duy nht u?
Th nht l Block gii hn scope (phm vi hot ng) ca mt variable
n khng ng chm ai d gy nn bug, th hai l trng hp in
hnh ta s cn feature ny l trong mt FOR...LOOP, c mi iteration ta
mun instantiate mt Object mi. Khi y ta cn Declare mt Object
variable, instantiate Object , ri cha n vo mt collection chng hn.
Truy cp Variable/Class/Structure
Trong VB.NET ta c th quyt nh gii hn vic truy cp mt Variable,
Class, Structure .v.v. bng cch dng cc keywords sau:
Loi truy
cp
Th d Ch thch
Public
Public Class
ClassForEverybody
Cho php u cng dng n c. Ta ch
c th dng Public mc Module,
Namespace hay File. Tc l ta khng th
dng Public trong mt Sub/Function.
Cc bi tp Microsoft .NET 49
Protected
Protected Class
ClassForMyHeirs
Cho php cc classes con, chu c dng.
Ta ch c th dng Protected mc
Class.
Friend
Friend
StringForThisProject As
String
Cho php code trong cng mt Project c
dng.
Private
Private
NumberForMeOnly As
Integer
Cho php code trong cng module, class,
hay structure c dng. Lu l Dim coi
nh tng ng vi Private, do ta nn
dng Private cho d c.
Ngoi ra, nh l nu container (Object cha) ca mt
Variable/Class/Structure l Private th d ta c tuyn b mt
Variable/Class/Structure nm bn trong container l Public ta cng khng
thy n t bn ngoi.
Thay i trong Array
Array index t 0
Trong VB.NET khng c Option Base v mi Array u c index bt
u t 0. Khi bn tuyn b mt array nh:
Dim myArray(10) As Integer
Kt qu l mt array c 11 elements v index t 0 n 10. UBound ca
array ny l 10 v LBound ca tt c arrays trong VB.NET u l 0.
Tuyn b Array vi nhng tr s khi u
Bn c th tuyn b Array vi nhng tr s khi u nh sau:
Dim myArray() As Integer = { 1, 5, 8, 16 } ' Note the curly brackets
Statement lm hai chuyn: quyt nh size ca array v cho cc elements
tr s khi u. dng feature ny, bn khng c ni r size ca
array, m cho program t tnh.
ReDim Preserve
Trong VB.NET bn cng c th tip tc dng Preserve keyword gi
nguyn tr s ca cc elements trong mt array khi bn ReDim n. Tuy
Cc bi tp Microsoft .NET 50
nhin c mt gii hn cho array vi hn mt dimension - bn ch c th
resize dimention cui (bn phi) , nn nhng hng code sau y hp l:
Dim myArray(,) As String
ReDim myArray(5, 5)
ReDim Preserve myArray(5, 8)
Thay i trong User-Defined Type
nim User-Defined Type (UDT) rt tin cho ta gom cc mnh data
lin h li thnh mt data type c cu trc. Trong VB6 ta dng n nh
sau:
Public Type UStudent
FullName As String
Age As Integer
End Type
VB.NET cng gi y c tnh ca UDT nhng thay i ch Type thnh
Structure:
Public Structure UStudent
Public FullName As String
Public Age As Integer
End Structure
Lu cc Structure Members (nh FullName , Age ) cn phi c
Declared vi keyword Dim, Public, Private hay Friend, nhng khng th
dng Protected v Structure khng th Inherit t mt Structure khc. S
d, c dng Private l v bn trong Structure c th c Property,
Sub/Function .v.v..
Thay i trong Collections
VB6 h tr Collection v sau ny Windows Scripting Host Library cho ta
collection kiu Dictionary. VB.NET cho ta mt thnh phn collection rt
hng hu trong Namespace System.Collections. V Collection l mt
trong nhng cng c rt thng dng v hiu nng trong VB.NET nn ta s
c mt bi dnh ring cho collection sau ny.
Cc bi tp Microsoft .NET 51
Di y l danh sch cc collections ta s dng thng xuyn:
Collection Chc nng
ArrayList Dynamic Array t ng ln ln khi elements c b vo.
BitArray Array cha tr s Boolean (True/False).
HashTable Collection cha nhng cp key-value data, cho ta dng lm t in.
Queue
Cha mt FIFO (First In, First Out) structure. Element c th l bt c
Object loi no.
Stack Cha mt LIFO (Last In, First Out) structure.
SortedList Cha mt danh sch nhng cp key-value data c sp theo th t.
Arithmetic Operators mi
VB.NET cho ta thm cch vit Arithmetic Operator mi m C
programmers rt thch t lu nay.
X += 4 tng ng vi X = X + 4
Mess &= " text" tng ng vi Mess = Mess & " text"
Arithmetic Operation Trong VB6 Cch vit tc mi
Cng X = X +5 X += 5
Tr X = X - 10 X -= 10
Nhn X = X * 7 X *= 7
Chia X = X / 19 X /= 19
Chia Integer X = X \ 13 X \= 13
Ly tha X = X ^ 3 X ^= 3
Ghp Strings X = X & "more text" X &= "more text"
Ta vn c th tip tc dng cch vit trong VB6, nhng by gi c thm
mt cch vit gn hn.
Cc bi tp Microsoft .NET 52
Short Circuit trong IF..THEN Statement
Trong VB6, nu ta vit:
Dim myInt As Integer
myInt = 0
If (myInt <> 0) And (17 \ myInt < 5 ) Then
Th s b Division by Zero error, v mc du phn (myInt <>0) l False,
nhng VB6 vn tip tc tnh phn
(17 \ myInt < 5 ), v to ra error v 17 chia cho mt s 0.
Trong vi ngn ng lp trnh khc, khi (myInt <>0) l False th n khng
tnh thm na, tc l n ni rng khi mt phn ca AND l False th nht
nh kt qu ca Logical Statement trong IF phi l False. c tnh ny
gi l Short-Circuit (i tc).
Nu ta dng code ni trn trong VB.NET, n vn cho Division by Zero
error ging nh VB6. Tuy nhin, nu ta mun dng c tnh Short-Circuit
th ta ch cn thay th ch And bng AndAlso nh sau:
Dim myInt As Integer
myInt = 0
If (myInt <> 0) AndAlso (17 \ myInt < 5 ) Then
Short-Circuit cng p dng cho Logical OR khi ta thay th ch Or bng
OrElse ni rng khi phn u ca OR l True th nht nh kt qu
ca Logical Statement trong IF phi l True.
Khng cn Set statement cho Object
Trong VB6 ta c th vit:
Set x = New Product
Set w = x
Trong VB.NET s c vit li nh sau:
Cc bi tp Microsoft .NET 53
x = New Product()
w = x
By gi ta khng cn phi nh dng ch Set khi ni n Object.
Thay i trong cch vit Property routines
Dng mt Property duy nht
Nu trong VB6 ta vit:
Private mdescription as String
Public Property Let Description (Value As String)
mdescription = Value
End Property
Public Property Get Description() As String
Description = mdescription
End Property
Trong VB.NET Let v Get uc hp li trong mt Property routine duy
nht v ta li dng ch Set thay cho ch Let (mc du ch Set khng cn
dng cho Object nh mi ni trn) nh sau:
Private mdescription As String
Public Property Description() As String
Set (ByVal Value As String)
mdescription = Value
End Set
Get
Description = mdescription
End Get
End Property
ReadOnly v WriteOnly property
By gi nu Property l ReadOnly ta s vit:
Cc bi tp Microsoft .NET 54
Public ReadOnly Property Age() As Integer
Get
Age = 3
End Get
End Property
hay WriteOnly ta s vit:
Private _data As Integer
Public WriteOnly Property Data() As Integer
Set (ByVal Value As Integer)
_data = Value
End Set
End Property
Default Properties
Ta dng Default keyword to ra Default Property nh sau:
Default Public Property Item(ByVal Index As Integer) As String
VB.NET bt buc ta phi t nht mt parameter cho Default Property.
Dng Reserved Word lm Procedure Name
Trong VB.NET ta c th dng Reserved Word lm Procedure Name bng
cch n gia ngoc vung. Gi t ta mun dng ch Compare lm tn
mt Function, ta s vit nh sau:
Public Function [Compare] (ByVal v1 As Integer, ByVal v2 As Integer) As Boolean
Structured Error Handling
TRY...CATCH...FINALLY
VB.NET cho ta Structure TRY...CATCH...FINALLY...END TRY x
l error. Th d nh trong bi ton chia di y, nu b Division by 0
error th ta s cho kt qu bng 0. D c error hay khng, program vn
hin th kt qu trong Output Window qua statement
Console.WriteLine( result) trong phn Finally:
Cc bi tp Microsoft .NET 55
Try
result = a / b ' if this section has error jump to Catch section
Catch
' only get here if an error occurs between Try and Catch
result = 0
Finally
' This section is optional, but is always executed whether there is an error or not
Console.WriteLine( result)
End Try
Nu ta khng code g phn Catch th c ngha l chng ta c Handle
Error nhng li khng lm g ht, do Program s khng t. Ngc li,
nu ta khng dng Try..Catch, th program s t.
Nu mun nhy ra khi Try Structure bt c lc no ta c th dng Exit
Try,
Nhng cch CATCH error
Ta c th dng Catch ging nh Select Case c mt cch x l cho
mi error:
Try
' Main code goes here
Catch When Err.Number=5
' handle Error 5
Catch
' handle other errors
End Try
Ta c th Catch Error Exception data trong mt variable dng n nh
sau:
Catch e as Exception
MessageBox.Show (e.ToString)
Hai cch code trn c th c gp li thnh:
Cc bi tp Microsoft .NET 56
Catch e As Exception When Err.Number = 5
Thay i trong cch vit Sub/Function
Dng du ngoc khi gi Procedure
Trong VB6, nu khng dng keyword Call ta khng dng du ngoc khi
gi Sub. Trong VB.NET ta lun lun dng cp du ngoc, ngay c khi
khng c parameter. Th d:
ProcessData()
x = New Customer()
ByVal l Default cho mi Parameters
Trong VB6, ByRef l default cho cc parameters passed v
Sub/Function. Tc l, Sub/Function c th v tnh lm thay thi tr s
nguyn thy ca parameter variables.
Trong VB.NET, ByVal l default cho cc parameters passed v
Sub/Function. Do , n s trnh li lm ni trn.
Optional Parameter cn c tr s Default
Trong VB6 ta c th dng IsMissing bit xem Optional parameter
c hin din khng. VB.NET b IsMissing v bt buc ta phi cung
cp tr s Default cho Optional parameter trong phn procedure
declaration ging nh sau y :
Public Sub VerifyInput (Optional ByVal InputData As String="")
trong th d ny ta cho Default value ca Optional parameter InputData l
Empty string.
Return Statement
Hy xem mt th d dng Function return mt Customer Object trong
VB6:
Public Function GetCustomer (ByVal CustID As Long) As Customer
Dim objCust As Customer
Set objCust = New Customer
objCust.Load CustID
Cc bi tp Microsoft .NET 57
Set GetCustomer = objCust
End Function
Trong VB.NET ta c th dng Return Statement Return kt qu ca
mt Function thay v dng chnh tn ca Function.
Public Function GetCustomer (ByVal CustID As Long) As Customer
Dim objCust As New Customer(CustID)
Return objCust
End Function
Delegate
Delegate l mt cch gip ta pass mt procedure nh mt parameter vo
trong mt method. nim ny c gi l Function Pointer hay
Callback. Mt trng hp c in ta dng Delegate l cung cp mt
dataArray sort vi mt Function so snh mi hai items trong array.
Trong VB.NET ta dng AddressOf operator pass mt procedure. Ta
declare mt Delegate bng cch ni n l mt procedure di dng no,
c bao nhiu parameters, mi parameter thuc loi data type no. Th d:
Delegate Function IsGreater (ByVal v1 As Integer, ByVal v2 As Integer) as Boolean
Khi vit code ta c yn tm s c cung cp mt Function c dng y v
i khi code nh sau:
Public Sub DoSort (ByRef DataArray() As Integer, Greater As IsGreater)
Dim outer As Integer
Dim inner As Integer
Dim temp As Integer
For outer = 0 To UBound(DataArray)
For inner = outer + 1 To UBound(DataArray)
If GreaterThan.Invoke( DataArray(outer), DataArray(inner)) Then
temp = DataArray(outer)
DataArray(outer) = DataArray(inner)
DataArray(inner) = temp
Cc bi tp Microsoft .NET 58
End If
Next
Next
End Sub
cch dng Method Invoke gi mt Delegate. By gi ta ch cn
cung cp Delegate routine m ta ha:
Public Function myIsGreater (ByVal v1 As Integer, ByVal v2 As Integer) as Boolean
Return ( v1 > v2)
End Function
Tip theo y l cch ta dng Delegate ni trn:
Dim myData() As Integer = { 2, 5, 8, 13, 26}
DoSort (myData, AddressOf myIsGreater)
Khi mt Subscriber registers vi mt Publisher mt routine Handle
mt loi Event, ta cng dng delegate nh sau:
AddHandler Button4.Click, AddressOf Button4_Click
Khi mt Event Click xy ra Button4, system s execute Sub
Button4_Click.
Cc bi tp Microsoft .NET 59
Bi 4
Nhng chc nng i Tng mi ca VB.NET
(phn I)
V B.NET khc phc nhng gii hn v i Tng (Object-Oriented)
ca VB6 v mang n cho ta mt ngn ng lp trnh hon ton Object-
Oriented (OO). Gn nh mi th trong VB.NET u lin h vi Object.
Nu bn cn mi vi lp trnh theo hng i tng (Object Oriented
Programming) th phn gii thch sau y s gip bn lm quen vi n.
Classes v Objects, nguyn tc Abstraction
Theo phng php i tng, program c thit k mt phn code
i din cho mt vt tng ng ngoi i. N c gi l Class.
Khi lp trnh VB6 ta dng nhng controls t Toolbox nh Textbox,
Label, Listbox ..v.v.. Textbox l Class ca cc Objects Text1, Text2.
Cng nh Label1, Label2 l nhng Objects to ra t Class Label. Ta hay
dng hai t Class v Object ln ln nhau. iu khng quan trng,
min l ta bit rng Class l mt nim Tru tng (Abstraction), cn
Object l mt vt thc hu. Ging nh Class CaS l mt nim tru
tng, cn Object KhnhH ca Class CaS l mt ngi bng da, bng
tht vi ting ht c nhiu ngi ngng m.
Ta ni Object l mt Instance ca Class, v ta instantiate Class c
mt Object.
Cc bi tp Microsoft .NET 60
Thng thng khi ta phn tch mt vn thit k chng trnh th
cc Danh t (Nouns) l nhng Classes. Gi d ta phn tch hot ng
ca mt Nh Kho (warehouse). Ta c phng cha, ngn t, bi nhn
hng, xe nng hng, nhn vin ..v.v., mi th u c th l mt Object
nn ta s thit k mt Class cho n.
Fields, Properties, Methods v Events, nguyn tc Encapsulation
Class CaS din t CaS l ngi nh th no. Nh SBiHt l mt
Public Variable ca Class, c gi l Field c th c c/vit trc
tip. Cn Kiu tc (di, ngn, mu en, c sc nu ...), Ging ht (cao,
trm, ..). l nhng Properties. Chng cng ging nh Field nhng c
implemented (thi hnh) bng cch dng procedures Property Get v
Property Set. Property Set c th c coded kim sot nu "Kiu
tc" khng thch hp th s b loi b. Ngc li, nu "Kiu tc" thch
hp v c p dng th ta s thy kt qu ngay l CaS li p thm ra.
Thng thng Fields v Properties l cc Danh t (Nouns).
Mt CaS c kh nng nCa, KTnLuNim, TrnhDin. Ta gi
l nhng Methods m ta implemented bng Subs v Functions (th d
nh Function KTnLuNim s return mt ch k). Thng thng
Methods l nhng ng t (Verbs)
i vi code bn trong Class th Property ging nh mt Method cn i
vi Client (tc l program ang dng Class) th Property ging nh
Field.
i khi, nu trnh din lu, CaS cn mt ly nc. CaS s Raise Event
Kht Nc nhn vin trong hu trng phc v.
Ta gi chung Fields, Properties, Methods v Events l nhng Class
Members (Cc Thnh vin ca Class)
C mt ngoi l v s khc bit gi Class v Member, l khi ta dng
cc Shared Class Members ca mt Class th ta khng nht thit phi
instantiate mt Object. Ta c th dng thng tn ca Class nh mt
Object.
Ci li im ca Object Oriented Programming l ta c th gi tt c
nhng c im, kh nng ca mt Class vo trong mt Unit of Code
(n v m) t tc. Khi chng ta lch s yu cu th CaS nCa. Ta bit
Cc bi tp Microsoft .NET 61
CaS ca th thu ht lng ngi, nhng ta khng cn bit lm sao CaS t
n trnh nh vy. khng phi l chuyn chng ta quan tm.
i vi ta Class CaS l mt Black Box, ta khng bit v khng cn bit
chuyn g xy ra bn trong. Nu sau ny CaS thay i k thut n ca
ht d v hay hn, iu khng nh hng g n chng ta. c tnh
OO y gi l Encapsulation (Gi kn).
Cch ta lp trnh vi Class ch khc cch ta lp trnh trc y mt cht
thi. Nu trc y ta phi t lm, th by gi ta instantiate mt Object
ca Class chuyn tr nhng chuyn ta mun lm, ri bo n lm cho ta.
So vi ngoi i, th d bn c m mt tim photocopy. Sau mt nm bn
t trng coi, cng chuyn lm n n nh v c kt qu tt. Bn mun m
thm mt tim photocopy na ch khc. Trc khi i lo ch khc bn
hun luyn ngh photocopy cho mt ngi lm cng trung thnh, ri giao
cho ngi y lm qun l thay th bn. Ngi l mt Object ca
Class QunLTimPhotoCopy.
Cc bi tp Microsoft .NET 62
Tr li cch lp trnh, nhng cng vic bn lm hng ngy trong tim
photocopy l nhng Methods. Tt c c, s sch ca tim l nhng
Properties. Bn sp t mi tun phi gi ngi li qut dn tim,
mi thng phi bo tr cc my photocopiers, l nhng Events. By
gi bn gi tt c nhng th y li thnh Class
QunLTimPhotoCopy. Ln u bn instantiate Class
QunLTimPhotoCopy lm thnh ChTThng, ngi s thay th bn
lm qun l tim photocopy u tin. Khi bn mun m thm tim th
ba, bn s instantiate Class QunLTimPhotoCopy mt ln na lm
thnh DSuHng , ngi s thay th bn lm qun l tim photocopy
th nh.
Khi phn chia trch nhim cc phn code thnh nhng Class, bn c
th tp trung t tng vo tng Class mt, khng cn phi c nh mi th
trong u khi gii quyt chuyn g. V code ca Class no ch lm vic v
nh hng trong phm vi hot ng ca n, khng ng chm n ai
khc. Nu c g trc trc, thng thng ta c th xc nh l li ca
Class no tng i d dng.
C mt cu hi a rng theo phng php OO th: "Thay mt bng n
cn bao nhiu programmers?". p: "Khng cn programmer no ht,
bn bo n t thay bng ca n." (Li p khc: "Khng cn
programmer no ht, Microsoft i tiu chun ra bng m.")
Do , nu trc kia bn lp trnh t mnh lo liu cng chuyn th by
gi hy giao cho cc Objects t lo cho chng. Tc l trc y, nu bn
l ch in mi nm bn phi i gp la rung, th by gi bn bo cc t
in phi t em np la vo trong kho cho bn. Sng khng? Ch
trong th gii lp trnh OO, ta mi c th m mng nh vy.
Inheritance (Tha K)
Nguyn tc Encapsulation ni trn cho php ta dng nhiu Objects ca
mt hay nhiu Classes mt cch an ton, tc l khng s Methods ca cc
Objects gim chn ln nhau.
Gi s ta mun dng li mt Class lm mt Class mi, c bit hn,
th d nh ta mun lm nn mt Class CaS t Class NghS. Cch lm
Cc bi tp Microsoft .NET 63
y gi l Inheritance (Tha k). Cng vic tha k ny c thc hin
qua mt qu trnh gi l Subclassing.
y ta dng li Class NghS m hon ton khng ng n Source
Code (Ngun M) ca Class NghS. Nguyn tc y gi l Reusability
(Dng li). Lu l nu ta dng li Source code m c sa i mt cht
trong Source Code th khng th gi l Reuse c v c th vic sa i
Source Code s gy ra bugs mi. Ta phi ch cn Inherit t Object
Code ca mt Class cng c th mi tht s l Reuse.
Ta dng Inheritance cho thm cc Class Members, tc l thm c tnh
v chc nng. Th d NghS th c Property TmHn (NhyCm
(Sentitive) , ThMng (Romantic),...), v Methods KTnLuNim,
TrnhDin. Class CaS s gi y cc c tnh v chc nng y v thm
Sub nCa, Function HtNhcYuCu, .v.v..
Tng t nh vy, ta cng c th tha k t Class NghS to ra Class
HaS. Class HaS s gi y cc c tnh v chc nng ca Class NghS
nhng thm Function VChnDung, Sub TrangTr.
Trong th d ni trn, ngi ta gi Class NghS l Parent Class, Super
Class hay Base Class. Cn Class CaS v Class HaS c gi l Child
Class hay SubClass.
Cc bi tp Microsoft .NET 64
Nu ta li Inherit Class CaS to ra Class CaSTnNhc v Class
CaSCNhc th trong trng hp ny CaS l Parent Class v
CaSTnNhc vi CaSCNhc l Child Classes.
Mi Cas l mt NghS nn ta c mi lin h "IS (L)" gia hai classes
ny. N khc vi mi lin h "HAS (C)". Th d nu trong Class CaS
c mt Object thuc Class uBp, th mt CaS c th cho ta mt ba
n ngon nhng khng hn cho chnh CaS nu. N ging nh ngoi i
CaS KhnhH mn mt u bp i khch. Ta s ni Class CaS c
mi lin h HAS (C) vi Class uBp trong trng hp ny, ch
khng phi Class CaS IS (L) mt Class uBp.
Trong .NET ta ch c Single (n) Inheritance, tc l mt Class khng
th Inherit t hai hay ba Classes khc. Ging nh ni Con tha k t Cha
v Cha tha k t ngNi, khng c nhc g n M hay BNi. Mt
Child Class ch c mt Parent Class, ngc li, mt Parent Class c th
c nhiu Child Classes.
Polymorphism (a dng)
Polymorphism l kh nng dng Class Members trng tn ca Objects
thuc v cc Classes khc nhau. Th d Objects KhchHng v
NhnVin u c Property Name. Nu ta c th lp trnh dng Name
Cc bi tp Microsoft .NET 65
m khng cn ni r n thuc v Object KhchHng hay NhnVin th
l Polymorphism.
Polymorphism th hin di nhiu hnh thc:
1. Late Binding (Hiu lc tr): C ngha l i n gi
cht, khi execution, th code mi bit n ang lm
vic vi loi Object no. Ch binding ni n "hiu
lc", late binding l c hiu lc tr. iu ny c
thc hin bng cch ha hn mt Object thuc Parent
Class trong lc runtime ta c th giao cho code mt
Object thuc Child Class. Th d ta ha vi khn gi
s c mt CaS trnh din, lc m mn ta c th cung
cp mt CaSTnNhc hay mt CaSCNhc.
2. Overloading (Qu ti, c ri m cn cho thm) :
Overloading cho php ta vit trong cng mt Class
nhiu versions khc nhau ca Property hay Method.
Chng c phn bit nh dng parameters khc data
type hay con s parameters khc nhau. Th d mt
version ca Sub c passed cho mt Integer
Parameter, mt version khc c passed cho mt
String Parameter, mt version khc li c passed
cho hai parameters. Khi ta gi mt Method ca Class,
n s da vo data type ca parameters ta pass v s
parameters ta pass execute ng version ca
Method.
Mt th d v Overloading ngoi i l khi ta yu cu
CaS n ca ta c php ngh CaS ht theo
Cc bi tp Microsoft .NET 66
Karaoke, hay c Ban Nhc Sng ph ha, hay thm
c mt nhm ca s khc ph ha .v.v..
3. Overriding (Ln quyn) : Overriding p dng cho
Child Class i vi Parent Class. Trong Child Class ta
cung cp mt Method cng tn, cng s parameters v
cng parameter data type vi mt Method trong Parent
Class ( y khng nht thit phi l Cha, c th l
ngNi hay nhiu i trc) dng n thay th cho
Parent Class Method. Ta ni Child Class thay i
behaviour (tnh tnh, cch x s) ca Parent Class.
i khi ging nh c LLin trc y Ht nhc
hi hc, by gi c KhnhH tha k t c nhng
override Method Ht ca c v c implement mt
Method Ht mi dng cho nhc tr tnh.
Lc runtime, nu mt Object khng c
implementation ca mt Method th CLR (Common
Language Runtime) s dng Method ca Parent Class
ca n. Trong th d trn v c KhnhH c mt
implementation cho method Ht nn system s dng
method , thay v dng method Ht ca c LLin.
Dng OO trong VB.NET
To mt Class mi
Bn to mt Class mi trong VB.NET IDE bng cch dng Menu
Command Project | Add Class. Dialog Add New Item s hin ra, chn
Class trong s hnh cc Icons nm trong khung bn phi ca Dialog.
Cc bi tp Microsoft .NET 67
Source code ca Class mi ny s c cha trong mt VB source file
vi extension vb. Trong VB.NET tt c mi VB source files u c
extension .vb. System s nhn din ra loi VB file (form, class,
module,.v.v..) nh c content ca file, ch khng da vo file extension.
Nu bn mun t tn cho Class mi ny l TheClass chng hn, th bn
c th sa tn n trong Dialog. Khi bn click button Open mt file mi s
c cho thm vo trong Project v n cha hai hng code sau:
Public Class TheClass
End Class
Cc bi tp Microsoft .NET 68
Bi 5
Nhng chc nng i Tng mi ca VB.NET
(phn II)
Dng OO trong VB.NET
To mt Class mi
Class Keyword
Trong mt .vb file ta c th vit nhiu Classes, code ca mi Class nm
trong mt Class ... End Class block. Th d:
Public Class TheClass
Public Sub Greeting()
MessageBox.Show("Hello world", MsgBoxStyle.Information, "TheClass")
End Sub
End Class
MessageBox.Show v MsgBoxStyle.Information trong VB.NET thay th
MsgBox v vbInformation trong VB6.
Classes v Namespaces
Nhc li l .NET dng Namespace sp t cc Classes cho th t theo
nhm, loi. Namespaces c declared vi mt Block Structure ging
nh sau:
Namespace Vovisoft
Public Class TheClass
Public Sub Greeting()
MessageBox.Show("Hello world", MsgBoxStyle.Information, "TheClass")
End Sub
End Class
End Namespace
Cc bi tp Microsoft .NET 69
Mun ni n bt c Class, Structure, hay th g c declared bn trong
mt Namespace...End Namespace block ta phi dng tn Namespace
trc. Th d:
Private myObject As Vovisoft.TheClass
Mt source file c th cha nhiu Namespaces, v bn trong mi
Namespace li c th c nhiu Classes.
Ngoi ra, Classes thuc v cng mt Namespace c th nm trong nhiu
files khc nhau trong mt VB.NET project.
Th d ta c mt source file vi code nh sau:
Namespace Vovisoft
Public Class TheClass
' Code
End Class
End Namespace
V mt source file khc trong cng project vi code:
Namespace Vovisoft
Public Class TheOtherClass
' Code
End Class
End Namespace
Vy th trong Namespace Vovisoft ta c hai Classes TheClass v
TheOtherClass.
Nh l, by default, Root Namespace ca mt VB.NET project l tn ca
project y. Khi ta dng Namespace block structure l chng ta ang thm
mt tng tn vo Root Namespace. Do , trong th d trn nu tn
project l MyProject th, t bn ngoi project y, ta c th declare mt
variable nh sau:
Private myObject As MyProject.Vovisoft.TheClass
Cc bi tp Microsoft .NET 70
To ra Methods
Methods trong VB.NET c hai th: Sub v Function. Function th phi
return mt kt qu. By default, parameters ca Method l ByVal ch
khng phi ByRef. Tc l nu mun parameter no ByRef th phi nh
khai ra r rng.
Nhc li l khi mt variable c passed vo trong mt method bng
ByVal th system cho method mt copy (bn sao) ca variable, do ,
tr s ca variable khng b thay i bi cng tc ca method. Ngc li,
nu mt variable c passed vo trong mt method bng ByRef th
method dng chnh variable , do , tr s ca variable c th b thay
i bi cng tc ca method.
Ta c th gii hn vic s dng mt method bng cch p t mt Access
Modifier (sa i quyn truy nhp) hay cn gi l Scoping keyword
(phm vi hot ng):
Private - ch cho php code trong cng Class c
gi.
Friend - ch cho php code trong cng
project/component c gi.
Public - cho php ai gi cng c.
Protected - cho php code trong subclasses (classes
con, chu) c gi.
Protected Friend - cho php code trong cng
project/component hay code trong subclasses c
gi.
To ra Properties
Trong VB.NET ta ch dng mt routine duy nht cho mi Property, vi
hai ch Get v Set nh sau (khng cn dng ch Let ca VB6 na):
Private mdescription As String
Public Property Description() As String
Set (ByVal Value As String)
mdescription = Value
Cc bi tp Microsoft .NET 71
End Set
Get
Description = mdescription
End Get
End Property
ReadOnly v WriteOnly property
By gi nu Property l ReadOnly ta s ly phn Set ra v vit:
Public ReadOnly Property Age() As Integer
Get
Age = 3
End Get
End Property
hay WriteOnly ta s y phn Get ra v vit:
Private _data As Integer
Public WriteOnly Property Data() As Integer
Set (ByVal Value As Integer)
_data = Value
End Set
End Property
Default Properties
Default Property l property ca Object m program dng khi ta ch cho
tn ca Object v khng ni r property no. Th d trong VB6 khi ta
code:
TextBox1 = "The house of rising sun"
VB6 hiu rng ta mun dng Default Property text ca Textbox1 nn
code y tng ng vi:
TextBox1.text = "The house of rising sun"
Trong VB6 khi ta dng keyword Set vi tn ca Object, th d nh:
Dim myTextBox As Textbox
Cc bi tp Microsoft .NET 72
Set myTextBox = TextBox1
program s hiu l ta mun ni n chnh Object myTextBox . Nu
khng th n bit ta mun ni n Object Default Property m lm bing
code cho r ra.
Trong VB.NET Default Property phi l mt Property array. Mt
Property array l mt property c Indexed (ni n tng Item bng
con s Index) ging nh mt array. L do chnh ca s bt buc ny l
khi ln ln gia hai trng hp ta ni n Default property ca mt
Object hay chnh Object y, v trong VB.NET ta khng cn dng Set
keyword cho Object assignment na (ta ch cn dng keyword Set trong
Property m thi).
By gi h mun ni n Default Property ca Object th phi dng
Index. Th d ni n chnh Object, ta code:
myValue = myObject
ni n Default Property Item 3 ca Object, ta code:
myValue = myObject(3)
S thay i t VB6 ny c ngha l mt property array procedure phi
nhn mt parameter. Th d:
Private theData(100) As String
Default Public Property Data(ByVal Index As Integer) As String
Get
Data = theData(Index)
End Get
Set(ByVal Value As String)
theData(Index) = Value
End Set
End Property
T nay ta khng th code:
TextBox1 = "Good morning!"
nh trong VB6 c na, m phi code:
Cc bi tp Microsoft .NET 73
TextBox1.text = "Good morning!"
V Property Text khng cn l Default Property ca TextBox.
Overloading methods
Mt trong nhng chc nng a din (Polymorphism) hng mnh nht ca
VB.NET l overload (qu ti, c ri m cn cho thm) mt method.
Overloading c ngha l ta c th dng cng mt tn cho nhiu methods -
min l chng c danh sch cc parameters khc nhau, hoc l parameter
dng data type khc nhau (td: method ny dng Integer, method kia dng
String), hoc l s parameters khc nhau (td: method ny c 2 parameters,
method kia c 3 parameters).
Overloading khng th c thc hin ch bng cch thay i data type
ca Return value ca Function. Phi c parameter list khc nhau mi
c.
Di y l th d ta dng Overloading code hai Functions tm data,
mt ci cho String, mt ci cho Integer:
Public Function FindData(ByVal Name As String) As ArrayList
' find data and return result
End Function
Friend Function FindData(ByVal Age As Integer) As ArrayList
' find data and return result
End Function
l ta c th cho mi overloading Function mt phm vi hot ng
(Scope on implementation) khc nhau. Trong th d trn ta dng Access
Modifier Public cho Function u v Friend cho Function sau.
Object Lifecycle
Object Lifecycle (cuc i ca Object) c dng ni n khi no
Object bt u hin hu v khi no n khng cn na. S d ta cn bit r
cuc i ca mt Object bt u v chm dt lc no l trnh dng n
khi n khng hin hu, tc l cha ra i hay khut bng ri.
Cc bi tp Microsoft .NET 74
New method
Trong VB6, khi mt Object thnh hnh th Sub Class_Initialize c
executed. Tng ng nh vy, trong VB.NET ta c Sub New(), gi l
Constructor. VB.NET bo m Sub New() s c CLR gi khi Object
c instantiated v n chy trc bt c code no trong Object.
Nu Sub Class_Initialize ca mt Class Object trong VB6 khng nhn
parameter th Sub New() trong VB.NET chng nhng c nhn parameters
m cn cho php ta nhiu cch gi n. S khc bit trong Constructors
ca VB6 v VB.NET rt quan trng.
Tng tng ta c mt Khun lm bnh bng lan; khun l Class cn
nhng bnh lm ra t khun s l cc Objects bnh bng lan. Nu ta
mun lm mt ci bnh bng lan vi mt lp s-c-la trn mt th cng
tc s gm c hai bc:
1. Dng khun (Class) nng mt ci Object bnh bng
lan (dng Sub Class_Initialize)
2. ln mt bnh mt lp s-c-la (dng class Public
Sub ThoaScla)
n y, mi chuyn tng i n tha. By gi, nu khch hng mun
mt ci bnh bng lan dng trng vt thay v trng g th ta chu thua
thi, v khng c cch no bo Sub Class_Initialize dng trng vt thay v
trng g ngay trong lc ang to dng ra Object bnh bng lan.
Sub New() trong VB.NET c th nhn parameters nn n c th nhn ch
th dng trng vt ngay trong lc nng ci Object bnh bng lan.
Ci dng n gin nht ca Sub New() m ta c th dng l khng pass
parameter no c (trong trng hp ny th ging nh Sub
Class_Initialize ca VB6). Ta code Sub New() trong Class nh sau:
Public Class BanhBongLan
Public Sub New()
' Code to initialise object here
End Sub
End Class
Cc bi tp Microsoft .NET 75
Ta instantiate mt Object bnh bng lan nh sau:
Dim myBanhBongLan As New BanhBongLan()
cho Users c s la chn khi instantiate Object, ta c th code thm
nhng Sub New khc, mi Sub dng mt danh sch parameter khc nhau.
Th d:
Public Class BanhBongLan
Public Sub New()
' Code to initialise object here
End Sub
Public Sub New(ByVal LoaiTrung As String)
Select Case LoaiTrung
Case "Vit"
' Code for TrngVt here
Case "Ga"
' Code for TrngG here
End Select
End Sub
End Class
Dng cng mt tn method implement nhiu methods khc nhau c
gi l overload. l mt trng hp a dng (polymorphism) ca OO
programming. Trong th d trn nu TrngVt v TrngG l hai loi
Data Types khc nhau th ta cng c th dng:
Sub New (ByVal TrngVt As TrngVtDataType)
instantiate bnh TrngVt v
Sub New (ByVal TrngG As TrngGDataType)
instantiate bnh TrngG.
Cc bi tp Microsoft .NET 76
Nh th ta khi bn tm vi Select Case LoaiTrung khi ch dng mt
Sub New duy nht vi 1 parameter.
Trong VisualStudio.NET, khi ta dng tn ca mt overloaded method,
IntelliSense s hin th hng dn ta nh vo parameter list khc
nhau ty theo method ta chn.
Termination
Trong VB6 mt Object s b hu dit khi ci reference (ch dng n
Object) cui cng b ly i. Tc l khi khng c code no khc dng
Object na th Object s b t ng hu dit. System gi mt counter
m s clients ang dng Object. Cch ny hay ch khi counter tr
thnh 0 th Object b hu dit ngay. Ta ni n c deterministic
finalization, ngha l ta bit r rng khi no Object bin mt.
Tuy nhin, nu ta c hai Object dng ln nhau (gi l circular
references), th ngay c n lc chng khng cn hot ng na, chng
vn hin hu mi trong b nh v ci Reference counter ca c hai
Objects khng bao gi tr thnh 0. Nu trng hp ny xy ra thng ln
ln system khng cn memory na, ta gi l memory leak (b r b
nh) .
.NET dng phng php khc qun l chuyn ny. C mi chc, mt
program s chy kim xem c Object no khng cn reference na
hu dit. Ta gi l Garbage Collection (nht rc). Ngay c trng
hp hai Objects c circular references nhng nu khng c code no khc
reference mt trong hai Objects th chng cng s c hu dit. C iu,
cng tc nht rc chy in the background (pha sau hu trng) vi u
tin thp, khi CPU rnh rang, nn ta khng bit chc mt Object s b hy
dit n bao gi mi tht s bin mt. Ta ni n c nondeterministic
finalization.
Ta c th p CLR nht rc lp tc bng code:
System.GC.Collect()
Tuy nhin, ta ch lm vic y khi kt qu thi. Tt hn, ta duyt li design
ca mnh cho php cc Objects ht xi c th ngi chi trong b nh
ch n lc c hy dit.
Cc bi tp Microsoft .NET 77
Dng Dispose Method
Nu ta c mt Object dng nhiu ti nguyn (resources) nh b nh,
database connection, file handle,.v.v. v ta cn phi th cc ti nguyn ra
ngay sau khi Object khng cn hot ng na, ta cn implement mt
Interface tn IDisposable vi Implements keyword nh sau:
Public Class TheClass
Implements IDisposable
Bn phi vit code cho Sub Dispose ging nh sau:
Private Sub Dispose() Implements IDisposable.Dispose
' Vit clean up code y th cc ti nguyn ra
End Sub
Sau bn vn phi vit code cho Client n gi Dispose Method trong
IDisposable interface. Bn cn phi dng CType cast Object Class khi
gi Dispose.
Dim objObject As New TheClass()
CType (objObject, IDisposable).Dispose()
ly i Reference n mt Object (gi l Dereference Object) bn c
th dng:
myObject = Nothing
l ta khng c dng keyword Set nh trong VB6. Nh l sau khi
statement trn c executed th myObject khng bin mt ngay nhng
n i Garbage Collector n gii quyt.
Tha k
Tha k (Inheritance) l kh nng ca mt Class t c interface
(giao din) v behaviours (tnh tnh) ca mt Class c sn. Ci qu trnh
lm nn vic y c gi l Subclassing. Khi ta to ra mt Class mi
tha k c interface ln behaviours t mt Class c sn l chng ta to
ra mt subclass ca Class nguyn thy. Ngi ta ni l mt mi lin
h is-a (l mt), ni Class mi l mt loi Class nguyn thy.
Ta phn bit mi lin h is-a vi mi lin h has-a (c mt). Trong mi
Cc bi tp Microsoft .NET 78
lin h has-a, Object ch c th lm ch mt hay nhiu Objects t, nhng
Object t l mt loi c th hon ton khc vi Object ch.
biu din c tnh Inheritance ta hy xt trng hp mt cng ty cung
cp Sn phm v Dch v. Ta c th code mt Class cho Sn phm
(ProductLine) v mt Class cho Dch v (ServiceLine) , ring r nhau.
Nhng v thy chng c nhiu im tng ng nn ta s code mt Class
gi l Mn hng (LineItem), ri inherit t LineItem ra ProductLine v
ServiceLine.
LineItem c cc properties ID, Item, Price (gi) v Quantity (s lng).
N cng c mt Public Function cho Amount (s tin).
Public Class LineItem
Private mintID As Integer
Private mstrItem As String
Private msngPrice As Single
Private mintQuantity As Integer
Public Property ID() As Integer
Get
Return mintID
End Get
Set (ByVal Value As Integer)
mintID = Value
End Set
End Property
Public Property Item() As String
Get
Return mstrItem
End Get
Set (ByVal Value As String)
Cc bi tp Microsoft .NET 79
mstrItem = Value
End Set
End Property
Public Property Price() As Single
Get
Return msngPrice
End Get
Set (ByVal Value As Single)
msngPrice = Value
End Set
End Property
Public Property Quantity() As Integer
Get
Return mintQuantity
End Get
Set (ByVal Value As Integer)
mintQuantity = Value
End Set
End Property
Public Function Amount() As Single
Return mintQuantity * msngPrice
End Function
End Class
to Class ProductLine t Class LineItem ta phi dng Inherits
keyword. Mi Object ProductLine l mt Object LineItem vi ProductID
v Description. ProductID ca ProductLine c pass vo Sub New lc
Cc bi tp Microsoft .NET 80
instantiate Object ProductLine. Cn Description l mt ReadOnly
property ca ProductLine. Ta c th code Class ProductLine nh sau:
Public Class ProductLine
Inherits LineItem
Private mstrDescription As String
Public ReadOnly Property Description() As String
Get
Return mstrDescription
End Get
End Property
Public Sub New(ByVal ProductID As String)
Item = ProductID
mstrDescription = "No description yet" ' Default description
' Vit code y c chi tit ca Product t Database
' trong c th c Description ca Product
End Sub
End Class
Statement Inherits LineItem khin ProductLine tha k mi interface v
behaviours ca LineItem. Do ta c th code mt Sub
BtnProduct_Click hin th chi tit ca ProductLine trong mt Listbox
nh sau:
Protected Sub BtnProduct_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles BtnProduct.Click
Dim pl As ProductLine
pl = New ProductLine("P1234")
ListBox1.Items.Add("ProductItem:" & pl.Item)
ListBox1.Items.Add("Description: $" & pl.Description)
Cc bi tp Microsoft .NET 81
End Sub
Trong code bn trn ta dng c property Item ca Class LineItem ln
property Description ca Class ProductLine. C hai u l property ca
ProductLine v n l mt SubClass ca LineItem.
Ging nh vy, mt ServiceLine c th c ghi ngy gi cung cp service.
Ta code Class ServiceLine nh sau:
Public Class ServiceLine
Inherits LineItem
Private mdtDateProvided As Date
Public Sub New()
' Make 1 as default number of services of this kind for invoice
Quantity = 1
End Sub
Public Property DateProvided() As Date
Get
Return mdtDateProvided
End Get
Set (ByVal Value As Date)
mdtDateProvided = Value
End Set
End Property
End Class
Mt ln na ta dng Statement Inherits ni rng ServiceLine l mt
SubClass ca LineItem. Ta thm property DateProvided vo interface
tha k t Class LineItem.
Cc bi tp Microsoft .NET 82
Bi 6
Nhng chc nng i Tng mi ca VB.NET
(phn III)
Dng OO trong VB.NET
Ngn cn Tha k
Bnh thng (By default) class no cng c th c dng lm base class
t ta tha k. Nhng i khi ta khng mun cho ai tha k t mt
Class no , lm vic y ta dng keyword NotInheritable khi declare
class:
Public NotInheritable Class KhngCon
End Class
Khi ta dng keyword NotInheritable ri th khng class no c th
dng keyword Inherits to mt subclass t class y.
Tha k v Phm vi hot ng
Khi ta dng c tnh tha k to mt SubClass th class mi ny c
mi methods, propertes v variables vi Access Modifier Public hay
Friend ca SuperClass. Bt c th g declared l Private trong
SuperClass th SubClass khng thy hay dng c.
C mt ngoi l l New method. Cc Constructor methods cn phi c
implemented (nh ngha)
li trong mi SubClass. Mt chc na ta s bn vo chi tit v im ny.
lm sng t vn SubClass c th dng Class Members no ca
SuperClass, ta th code li Function Amount trong LineItem class bng
cch khin n gi mt Private Function tn CalculateAmount tnh ra
Amount thay v n tnh trc tip nh trc y:
Public Function Amount() As Single
Return CalculateAmount
End Function
Cc bi tp Microsoft .NET 83
Private Function CalculateAmount() As Single
Return mintQuantity * msngPrice
End Function
Khi ta SubClass LineItem to ra ServiceLine class, bt c Object
ServiceLine no cng tha k Function Amount v Function y c
declared Public trong BaseClass LineItem. Ngc li, v Function
CalculateAmount l Private nn c ServiceLine class ln bt c client
code no dng mt LineItem Object u khng truy cp n c.
Nh th, mc du ta gi Function Amount c, nhng n phin n gi
Private Function CalculateAmount th c b tr ngi khng? Khng sao
c. V Function Amount nm trong cng Class vi Private Function
CalculateAmount nn n c th gi c, d rng ta gi Function
Amount t ServiceLine hay client code.
Th d trong client code ta c nhng hng code nh sau:
Protected Sub BtnShowAmount_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles BtnShowAmount.Click
Dim Service As ServiceLine
Service = New ServiceLine()
Service.Item = "Delivery"
Service.Price = 50
Service.DateProvided = Now
MessageBox.Show (Service.Amount.ToString, "Amount", MessageBoxButtons.OK,
MessageBoxIcon.Information)
End Sub
Kt qu s c hin th trong message box, cho thy Function
CalculateAmount c Function Amount gi dm cho client code d
rng c client code ln ServiceLine code u khng th gi trc tip
c.
im ny nhc ti nh li khi cn b, c ln b con trong vn em ra
ch cho ba m ti c thng xoi thm rt ngon. Bn ti li xm thy
Cc bi tp Microsoft .NET 84
vy biu ti ln ly hai tri xoi n vn. V khng phi l ngi nh
nn bn ti khng th ly uc xoi, bi Access Modifier ca thn xoi l
Private trong nh ti. Nhng v ti l Public, nn bn ti c th nh ti
ly dm.
Protected Methods
i khi Public hay Private thi cha . Nu ta declare th g Private th
n hon ton gii hn trong class, ngc li nu ta declare n Public (hay
Friend) th n c th c dng trong subclasses hay client code.
Tuy nhin, c lc ta mun mt class member ch c th c dng trong
subclasses thi, ch khng cho client code dng. Trong trng hp y ta
dng keyword Protected. Th d:
Public Class FatherClass
Protected DiSn As Single
End Class
Public Class SonClass
Inherits FatherClass
Public Function ChiaCa() As Single
Return Disn
End Function
End Class
y ta c BaseClass FatherClass vi Protected Field Disn. Khng
c client code no c th thy Field DiSn c. Th nhng bt c
SubClass no ca FatherClass cng u tha k v dng c DiSn.
Trong th d trn, mt ln na SubClass c mt Public method (ChiaCa)
c th return mt protected value - nhng chnh value y, DiSn, khng
trc tip cho php client code dng.
Overriding Methods
Chng ta bit rng c tnh quan trng ca Inheritance l mt SubClass
chng nhng tha k behaviours ca ParentClass m cn c th override
Cc bi tp Microsoft .NET 85
(ln quyn) cc behaviours y na. Chng ta thy mt SubClass c th
extend (thm ra) ParentClass bng cch cho thm cc methods Public,
Protected v Friend. Hn na, khi dng overriding, mt SubClass c th
alter (sa i) behaviours ca cc methods trong ParentClass.
Bnh thng (By default), ta khng th override methods trong
ParentClass tr khi cc methods y c declared vi keyword
Overridable trong ParentClass. Th d:
Public Class ClassCha
Public Overridable Sub ChoHi()
MessageBox.Show("Cho cc chu", "Class Cha")
End Sub
End Class
Tip theo, khi to mt SubClass, nu mun ta c th override behaviour
ca Sub ChoHi bng cch dng keyword Overrides nh sau:
Public Class ClassCon
Inherits ClassCha
Public Overrides Sub ChoHi()
MessageBox.Show("Tha cc Bc", "Class Con")
End Sub
End Class
By gi ta c th vit client code nh sau:
Private Sub BtnSubClassObject_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles BtnSubClassObject.Click
Dim obj As New ClassCon()
obj.ChoHi()
End Sub
Khi ta click button BtnSubClassObject program s hin th message
dialog di y:
Cc bi tp Microsoft .NET 86
Virtual Methods
Tuy nhin, hy xem trng hp ta code nh sau:
Private Sub BtnParentClassObject_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles BtnParentClassObject.Click
Dim obj As ClassCha
obj = New ClassCon()
obj.ChoHi()
End Sub
Trc ht, y c v k k, ti sao declare mt variable loi ClassCha
m li instantiate mt object ClassCon. Chuyn hon ton bnh
thng, v ClassCon l mt ClassCha. Tc l mt variable loi ClassCha
hay ClassCon u c th cha, tht ra l hold references to (point to, ch
ti), mt instance ca ClassCon.
im ny p dng tng qut khi ta dng Inheritance. Mt variable loi
SuperClass c th hold reference to bt c SubClass Object no tha k
t SuperClass y. l mt cch ta implement tnh a dng
(polymorphism).
u c th lm ta ngc nhin l khi ta click button BtnParentClassObject
ta cng thy hin th message " Tha cc Bc".
Cc bi tp Microsoft .NET 87
Sao l vy? Variable obj c declared l ClassCha ti sao message
khng phi l "Cho cc chu"? L do l Sub ChoHi ca ClassCon
c gi thay v Sub ChoHi ca ClassCha. Ta ni Sub ChoHi l
Virtual method. Tt c methods trong VB.NET u l virtual.
nim virtual ni rng ci implementation ca con chu tr nht
trong dng h c dng - khng cn bit l variable c data type l
class ca th h no trong dng h. Tc l, nu variable dng trong client
code hold references to ClassngNi, ClassCha, ClassCon hay
ClassChu th method trong ClassChu c gi. Nu trong ClassChu
khng c implementation ca method th ta gi method trong ClassCon,
nu khng c th gi method trong ClassCha .v.v.. theo th t t b di
ln b trn.
Keyword Me
Keyword Me c dng khi ta mun ni r (explicitly) rng ta mun
dng method ca chnh ci Class ang cha code y, ch khng phi mt
implementation no khc ca method y.
Cng c trng hp ta phi dng keyword Me ni ta mun dng class-
level variable ch khng phi procedure-level variable c cng tn. Mt
procedure-level variable, tc l local variable ca mt method, c cng
tn vi mt class-level variable c gi l shadowed variable. Th d:
Public Class TheClass
Private strName As String
Public Sub DoSomething()
Dim strName As String
Cc bi tp Microsoft .NET 88
strName = "Quang"
End Sub
End Class
y, variable strName c declared class-level v bn trong Sub
DoSomething. Bn trong method y local variables (k c shadowed
variables) s c dng v chng che y class-level variables tr khi ta
ni r rng phi dng variable ca class-level bng cch dng keyword
Me:
Public Class TheClass
Private strName As String
Public Sub DoSomething()
Dim strName As String
strName = "Quang" ' thay i value ca local (shadowed) variable
Me.strName = "Kim" ' thay i value ca class-level variable
End Sub
End Class
Keyword MyBase
Keyword Me rt tin dng khi ta mun dng Class members ca chnh
Class cha code. Tng t nh vy, i khi ta mun dng Class method
ca BaseClass (cng gi l SuperClass), ch khng phi mt
implementation ca method y trong SubClass. Nh l mt virtual
method lun lun gi implementation ca Class tr nht.
T trong mt SubClass, nu mun gi mt method ca BaseClass ta dng
keyword MyBase nh sau:
Public Class ClassCon
Inherits ClassCha
Public Overrides Sub ChoHi()
MessageBox.Show("Tha cc Bc", "Class Con")
MyBase.ChoHi()
End Sub
Cc bi tp Microsoft .NET 89
End Class
By gi nu ta chy Sub ChoHi ca ClassCon ta s c hai messages,
mt ci t ClassCon theo sau bi mt ci t ClassCha.
MyBase ch ni n BaseClass trc tip, tc l Class cha thi ch khng
ni n Class ng ni. Khng c cch no ni n hn mt th h.
Du vy, keyword Mybase c th c dng cho bt c th g c
declared Public, Friend hay Protected trong ParentClass. iu ny k
lun c nhng th m ParentClass tha k t cc th h trc trong gia
nh, tc l ClassngNi, ClassngC .v.v..
Keyword MyClass
V l do virtual method, ta s gp nhng trng hp rc ri nh khi code
ca ParentClass li chy code ca SubClasses.
Khi vit code ca mt class, t method ny ta thng gi nhng methods
khc nm trong cng class. Th d nh:
Public Class ClassCha
Public Sub V()
ChoHi()
End Sub
Public Overridable Sub ChoHi()
MessageBox.Show("Cho cc chu", "Class Cha")
End Sub
End Class
Trong trng hp ny, V gi Sub ChoHi n tip. l v
ChoHi c declared Overridable nn rt c th mt SubClass s
implement method ChoHi v ln quyn n. Th d:
Public Class ClassCon
Inherits ClassCha
Public Overrides Sub ChoHi()
MessageBox.Show("Tha cc Bc", "Class Con")
Cc bi tp Microsoft .NET 90
End Sub
End Class
V c tnh virtual ca ChoHi nn ta tng ClassCha execute chnh Sub
ChoHi ca n nhng t ra n li execute code ca ChoHi trong
ClassCon. Trong code di y, mt Object ClassCon gi Sub V ca
ClassCha:
Private Sub BtnSubClassObject_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles BtnSubClassObject.Click
Dim obj As New ClassCon()
obj.V()
End Sub
Trong ClassCha, Sub V gi ChoHi ca chnh n, tuy nhin Sub
ChoHi y b overridden bi implementation ca ChoHi trong
ClassCon. Do , program s hin th message "Tha cc Bc".
Nu ta khng mun nh vy, ta mun V execute chnh code ca
ChoHi trong ClassCha th phi dng keyword MyClass nh sau:
Public Class ClassCha
Public Sub V()
MyClass.ChoHi()
End Sub
Public Overridable Sub ChoHi()
MessageBox.Show("Cho cc chu", "Class Cha")
End Sub
End Class
y ta khng th dng keyword Me v V c gi ChoHi class-
level trong ClassCha ch khng phi trong mt SubClass, nhng b
overridden. Hnh di y minh ha qu trnh gi V t client code:
Cc bi tp Microsoft .NET 91
Sub V tht ra nm trong ClassCha m ClassCon tha k nn V
c executed trong ClassCha v gi Sub ChoHi trong cng class (
ClassCha). Nhng v ClassCon c mt implementation ca Sub ChoHi
nn n overrides ChoHi ca ClassCha.
Overridding Method New
Chng ta thy ta c th override methods v dng cc keywords Me,
MyBase v MyClass gi cc overriden methods trong dy chuyn tha
k. Tuy nhin, i vi Constructor ca class th c nhng lut l c bit
dnh ring cho method New.
Nhng methods New khng t ng di truyn t BaseClass xung
SubClass. Mi SubClass phi c mt implementation ring cho
Constructor d rng, nu mun, n c th gi vo BaseClass vi keyword
MyBase:
Public Class ClassCon
Inherits ClassCha
Public Sub New()
MyBase.New()
' thm cc code khc initialise ti y
End Sub
End Class
Cc bi tp Microsoft .NET 92
Khi gi Constructor ca BaseClass, ta phi gi n trc nht - nu khng
s b error. Tuy nhin ta khng cn gi Constructor ca BaseClass v
Constructor ca BaseClass c gi t ng.
C mt lut c bit l nu tt c methods New trong BaseClass u i
hi parameters th ta phi implement t nht mt method New trong
SubClass v ta phi t statement MyBase.New ngay pha u.
D nhin l ta c th Overload method New trong SubClass, nhng ta
phi t lo liu cch gi mt method New thch hp trong BaseClass.
To BaseClasses v Abstract Methods
Cho n gi ta bn v virtual method vi c tnh override trong
nguyn tc tha k. Trong cc th d trc y BaseClass c
instantiated thnh Object lm chuyn ny, chuyn kia. Nhng i khi
ta mun to mt BaseClass ch dng cho tha k m thi.
Keyword MustInherit (Phi c Tha K)
Tr li ci th d v Inheritance vi Class LineItem. S d ta t ra Class
LineItem l v n cha nhng th chung cho c hai classes ProductLine
v ServiceLine. Ch tht ra mt Object ca Class LineItem khng cha
mi c tnh lm mt vic g thc t. Nu ta mun ni r rng Class
LineItem ch c dng to nhng SubClasses bng cch tha k t
n, ta c th declare nh sau:
Public MustInherit Class LineItem
Tc l ta ch thm keyword MustInherit thi, ch khng thay i g
khc. Kt qu l t nay Client code khng th instantiate mt Object t
Class LineItem. Do dng code sau s b syntax error:
Dim myObject As New LineItem()
Thay vo , nu mun dng LineItem ta phi to SubClass t n.
Keyword MustOverride (Phi b Ln Quyn)
Tng t vi nim Phi-c-tha-k trong Class, ta cng c
MustOverride cho mt method. C th trong BaseClass ta khai bo mt
method, nhng ta i hi method y phi c mt implementation trong
SubClass. Ta declare nh sau:
Cc bi tp Microsoft .NET 93
Dim MustOverride Sub CalculatePrice
l y khng c thn th ca Sub CalculatePrice hay statement
End Sub g c. Khi dng MustOverride ta khng c php cung cp mt
implementation cho method trong BaseClass. Mt method nh th c
gi l abstract method hay pure virtual function, v n ch c phn
khai bo ch khng c phn nh ngha. Nhng abstract methods phi
c overridden trong bt c SubClass no ca BaseClass th mi dng
c. Nu khng, ta s khng c phn implementation ca method u c
v khi compile s gp syntax error.
Abstract Base Classes
Nu hp c hai nim MustInherit v MustOverride li ta s to ra mt
abstract base class. y l mt Class ch c khai bo ch hon ton
khng c implementation. Ta phi SubClass t n th mi lm vic c,
th d nh:
Public MustInherit Class ClassCha
Public MustOverride Sub V()
Public MustOverride Sub ChoHi()
End Class
K thut ny rt thch hp ta code ci sn hay b cc ca program
ngay trong lc thit k. Class no tha k ClassCha th phi implement
c Sub V ln Sub ChoHi, nu khng s b syntax error.
Nhn v mt phng din, abstract base class rt ging khai bo Interface.
Nu dng Interface, chng ta c th khai bo nh sau:
Public Interface ICha
Sub V()
Sub ChoHi()
End Interface
Bt c class no chu implement interface ICha th phi implement c
Sub V ln Sub ChoHi, nu khng s b syntax error - do , ta
thy Interface rt ging mt abstract base class.
Cc bi tp Microsoft .NET 94
S khc bit chnh gia abstract base class vi Interface l ch tha k.
Khi ta to mt class con bng cch SubClass t ClassCha, chnh class con
y li cng c th c SubClassed. My class chu ny s t ng tha
k V v ChoHi t class con.
Trong khi y ni v Interface, mi class phi t implement ICha mt cch
c lp v phi cung cp hai Subs V v ChoHi ca chnh n. V
th, nu ta khng c nh dng li code ca cc Subs khi ta to cc
classes mi th ta c th dng interface. Ngc li nu ta mun dng li
code trong SubClass theo nguyn tc tha k th ta nn dng abstract base
class.
Cc bi tp Microsoft .NET 95
Bi 7
Nhng chc nng i Tng mi ca VB.NET
(phn IV)
Dng OO trong VB.NET
Shared class members ( Cc thnh vin dng chung ca class)
Mc d Object rt hiu nng v hu ch, c khi ta ch mun truy cp cc
variables hay methods ca mt class lm vic m khng cn phi
instantiate mt Object no c. Tc l y nh trong qu kh, khi vit VB6,
ta dng cc variables hay methods ca mt BAS Module. i khi ging
nh thay v k giao ko vi mt thu (Object) thc hin mt cng
trnh, ta ch mun mn th hay chuyn vin lm vic gia cng ( gi cc
methods) thi.
Shared Methods
Trong VB.NET chng nhng mt Class c cc methods v properties
thng thng nh ta thy - tc l nhng methods v properties ca
mt Object ta c th dng ngay sau khi Object y thnh hnh qua qu
trnh instantiation - m cn c cc methods v properties ta c th dng
m khng cn phi to ra mt instance no t Class. Chng c gi l
shared methods. ( Trong cc ngn ng lp trnh khc cc methods ny
cn c gi l static methods hay class methods).
Ta khng th truy cp mt shared method qua mt Object nh method
bnh thng, nhng phi dng trc tip tn ca class. Th d sau y s
minh ha iu ny:
Public Class Math
Shared Function Add( ByVal x As Single, ByVal y As Single) As Single
Return x + y
End Function
End Class
Sau khi nh ngha Class Math, ta c th dng Shared Function Add
m khng cn instantiate mt Object thuc class Math nh sau:
Cc bi tp Microsoft .NET 96
Dim Result As Single
result = Math.Add(12.5, 36.8)
thay v dng mt object variable ta dng thng tn ca class Math
truy cp method Add. Vi mt method bnh thng th lm nh th s b
syntax error, nhng trong trng hp ny th khng sao.
Ta cng c th overload shared methods, tc l c th code nhiu shared
methods vi cng mt tn nhng c nhng parameter lists khc nhau.
Phm vi hot ng bnh thng (Default Scope) ca shared methods l
Public. Tuy nhin ta c th gii hn vic truy cp chng bng cch dng
nhng Access Modifiers nh Friend, Protected hay Private. Tht ra khi
overloading mt shared method ta c th dng nhng scopes khc nhau
cho mi shared method.
C mt th d v shared method t .NET system class libraries. m
mt text file theo mode input, in hnh ta dng shared method trong File
class nh sau:
Dim inFile As StreamReader = File.OpenText("words.txt")
Dim strIn As String
strIn = inFile.ReadLine()
y khng c object File no c to ra. Method OpenText l mt
shared Function, n m input text file words.txt v cho ta mt object loi
StreamReader tn inFile ta dng sau .
Shared Variables
i khi ta mun tt c objects ca cng mt class u dng chung mt
variable. Ta c th thc hin vic y vi shared variables.
Mt shared variable c khai bo vi keyword shared ging nh shared
method:
Public Class MyCounter
Private Shared mintCount As Integer
End Class
Cc bi tp Microsoft .NET 97
Ta c th cho shared variable mt scope Public hay Private ty , nhng
By Default, scope ca shared variables l Private, khc vi shared
methods th By Default l Public.
im quan trng ca shared variables l chng c dng chung gia
mi instances (objects) ca cng mt class. Di y l mt th d trong
ta gi ci counter c tr s tng thm 1 mi ln c mt instance mi
ca class MyCounter. Bt c lc no ta cng c th bit c bao nhiu
objects c to ra bng cch c property Count:
Public Class MyCounter
Private Shared mintCount As Integer
Public Sub New()
mintCount += 1
End Sub
Public ReadOnly Property Count() As Integer
Get
Return mintCount
End Get
End Property
End Class
Nh th, nu ta chy client code di y n s hin th kt qu l 3:
Protected Sub Button1_Click( ByVal sender As Object, ByVal e As System.EventArgs) Handles
Button1.Click
Dim obj As MyCounter
obj = New MyCounter()
obj = New MyCounter()
obj = New MyCounter()
MsgBox(obj.Count, MsgBoxStyle.Information, "Counter")
Cc bi tp Microsoft .NET 98
End Sub
Nu ta chy code thm hai ln na, ta s c 6 v 9. H ta cn chy
chng trnh th ci counter cn lm vic. Khi ta chm dt chng trnh
th ci counter s bin mt.
Global values
Mt cch dng rt thng dng khc ca shared variable l xem n nh
mt loi Global variable. Khi dng scope Public ta s c mt dng tng
ng vi VB6 Global variable trong mt BAS Module. Th d nh:
Public Class GlobalData
Public Shared TotalCost As Single
End Class
Sau ta c th dng variable ny khp ni trong client code:
GlobalData.TotalCost += 45.60
Events
Raising Event x l trong mt Project khc
VB.NET khng h tr Events t i cha n i con theo ng nguyn
tc tha k. Nu mt BaseClass nh ngha mt Public Event th ta ch c
th raise event y trong code ca BaseClass thi ch khng th raise
event y trong SubClass no ca BaseClass y.
Khc vi methods, ta khng th overload mt Event, tc l khng th
dng mt tn cho hai Events c parameter list khc nhau.
Ta c th to mt Class Library Project vi mt Class trong c raise
mt Event ri to mt project khc trong c code n nhn v x l
Event y.
th vic ny bn hy to mt Class Library Project mi vi tn
ClassLibrary1 v vit nhng dng code nh ngha Class Class1 vi
Event TheEvent v Sub LmVic raise Event nh sau:
Public Class Class1
Public Event TheEvent()
Cc bi tp Microsoft .NET 99
Public Sub LmVic()
RaiseEvent TheEvent()
End Sub
End Class
K bn dng Menu command File | Add Project | New Project
thm mt project mi vi tn EventClass. c th dng Class1, bn
cn phi reference n vi Menu command Project | Add Reference...,
chn Tab Projects v click Browse chn ClassLibrary1.DLL t
subfolder ClassLibrary1\bin ca solution nh trong hnh di y:
Mt khi referenced ClassLibrary1 vi Class1 trong y, by gi bn c
th doubleclick ln Form1 code nh sau:
Private WithEvents obj As ClassLibrary1.Class1
Private Sub Form1_Load( ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
obj = New ClassLibrary1.Class1()
End Sub
Cc bi tp Microsoft .NET 100
Nh l ta phi declare variable obj thuc loi ClassLibrary1.Class1 vi
WithEvents. t mt Button tn BtnLmVic v doubleclick ln n
code nh sau:
Private Sub BtnLmVic_Click( ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles BtnLmVic.Click
obj.LmVic()
End Sub
x l Event ca obj bn chn tn t combobox pha trn bn tri, ri
chn TheEvent t combobox bn phi nh trong hnh di y:
y ta handle Event bng cch hin th mt message n gin: ang
x l mt Event t Class1. By gi bn c th chy program. Khi bn
click Button BtnLmVic program s hin th message chng minh
rng t mt Application ta c th handle event trong Class ca mt
Project khc.
Cc bi tp Microsoft .NET 101
Ghi ch
Nu sau khi Unzip source file v load project vo, bn dng IDE Menu
command Build | Rebuild Solution compile li ht cc modules
nhng gp error v references th hy lm nh sau:
Trong Solution Explorer click cc tree nodes
references tm cc references c du chm thang
trong tam gic vng v remove chng.
Dng Menu command Project | Add Reference...
chn *.dll li t mt \bin subfolder.
Rebuild Solution.
Nu bn dng ch Vit Unicode trong program th nh set up Advanced
Save Option vi Menu command File nh trong hnh di y:
Cc bi tp Microsoft .NET 102
Khi Dialog hin ra, bn chn Unicode (UTF-8) cho Encoding:
Nu bn khng thy c menuItem Advanced Save Option trong Menu
File th c dng menuItem Save As... ri click ln combo box Save pha
di, bn phi ca Save File As Dialog ri chn Save with Encoding...
nh trong hnh di y:
Cc bi tp Microsoft .NET 103
Nu bn qun set up Advanced Save Option nh trn, ch Vit s b lu
tr di dng ANSI nn mt s s mt du ch Vit v thay vo bng
nhng du ?.
Shared Events
Events c th c declared l Shared. Shared methods ch c th raise
shared events, chng khng th raise non-shared events. Th d nh:
Public Class NgunEvent
Shared Event EventDngChoSharedMethods()
Public Shared Sub DngChung()
RaiseEvent EventDngChoSharedMethods()
End Sub
End Class
Mt shared event c th c raised bi c shared methods ln non-
shared methods:
Public Class NgunEvent
Public Event TheEvent()
Cc bi tp Microsoft .NET 104
Shared Event EventDngChoSharedMethods()
Public Shared Sub DngChung()
RaiseEvent EventDngChoSharedMethods()
End Sub
Public Sub LmVic()
RaiseEvent TheEvent()
RaiseEvent EventDngChoSharedMethods()
End Sub
End Class
Nu bn tm cch raise mt non-shared event t mt shared method th s
b syntax error.
Early Binding hay Late Binding (Hiu lc Sm hay Tr)
Early Binding c ngha l program bit r ngay t u loi Object (thuc
Class no) s c dng trong hon cnh no. N cho php IntelliSense
hin th cho ta thy nhng class members no ta c th dng v compiler
kim xem nhng methods ta dng c hin hu khng. Early Binding code
c compiled ra IL rt hiu nng v compiler bit r rng data types ca
cc parameters.
Ngc li Late Binding c ngha l ta lm vic cch linh ng vi mt
Object lc run-time, tc l program khng bit trc Object y thuc loi
no. Late Binding cho ta s uyn chuyn ch lm sao Object cung cp
ng method cn thit l . Do , ta khng hng c s sang trng
IntelliSense cung cp v compiler khng th kim sot loi Object trc
dm cho ta c. Mc du Late Binding code chy chm hn nhng n
cho ta s t do ging nh khi lm vic ngoi i, n gi cht mi xc
nhn.
By Default, mi objects trong VB.NET u l Late Bound. Visual
Studio.NET IDE vi Option Strict Off by default p t lut . Nu
mun p t Early Binding ta cn phi nht cu Option Strict On u
mt source file.
Cc bi tp Microsoft .NET 105
Dng Object Type
Ta c Late Binding khi compiler khng th xc nh loi Object ta ang
gi. Ta c th thc hin iu ny bng cch dng Object Type tuyn
b mt cch m h rng ta s dng mt loi Object no , v mt
variable vi Object type c th hold-reference-to bt c mt Object no.
Do , nhng dng code sau y c th c dng cho bt c Object no
m Class ca n c implement Sub CngTcTi v khng dng
parameter no c:
Option Strict Off
Module LateBind
Public Sub LmVic( ByVal obj As Object)
obj.CngTcTi()
End Sub
End Module
Nu obj passed vo Sub LmVic khng c mt Sub CngTcTi
chng dng parameter no ht th program s b error lc run-time. Do ,
ta nn lun lun dng mt Try Structure bt ci error . Th d nh:
Option Strict Off
Module LateBind
Public Sub LmVic( ByVal obj As Object)
Try
obj.CngTcTi()
Catch e As Exception
' Code x l trng hp Object khng thch hp
Console.WriteLine("Invalid Object passed to LmVic")
End Try
End Sub
End Module
Late Binding v Reflection
Cc bi tp Microsoft .NET 106
.NET framework h tr mt nim gi l reflection. N ni n kh
nng ca program kim tra .NET code bit trong code c nhng th g.
Ta dng namespace System.Reflection vit code lm chuyn y.
Vi System.Reflection ta c th vit code khm ph nhng classes
nm trong mt assembly, bit mi class c nhng methods, properties
v events no. Tip theo , ta c th dng reflection instantiate v
dng nhng objects t cc classes y. C qu trnh ny hon ton linh
ng - ging ht nh Late Binding.
Tht ra, CLR (Common Language Runtime) dng reflection implement Late
Binding dm cho chng ta. Thay v bt chng ta phi t dng reflection code Late
Binding, .NET t t lo lng chuyn y mt cch t ng cho chng ta.
Dng Function CType
Du ta c dng Late Binding hay khng, nhiu khi rt tin ta pass
reference n mt object no , t ch ny n ch khc, bng cch
dng Data Type Object tng qut - khi no cn dng n th ta i n ra
ng loi Object trong hon cnh. Ta thc hin vic convert data type
bng cch dng Function CType, iu cho php ta ni trc Data
Type Object s c converted ra object ca class no gi mt method
theo cch Early Bound:
Module LateBind
Public Sub LmVic( ByVal obj As Object)
CType(obj, TheClass).CngTcTi()
End Sub
End Module
Trong th d trn d rng ta ang lm vic vi variable thuc type Object
- trn nguyn tc th c v l Late Bound - nhng chng ta ang dng
Function CType convert obj ra mt object thuc class TheClass.
K thut ny c gi l casting ( khun). Nu ta xem TheClass nh
mt ci khun, khi ta p obj vo khun y th ging nh khun cho
obj c dng ca TheClass.
Function CType rt hu dng khi ta lm vic vi nhng objects c
implement nhiu interfaces, v ta c th dng cng mt object cho nhng
Cc bi tp Microsoft .NET 107
interfaces khc nhau. Gi d nh ta c mt object thuc loi TheClass v
n cng c implement mt interface tn MyInterface, ta c th dng
interface y trong code sau y:
Dim obj As TheClass
obj = New TheClass
CType(obj, MyInterface).DoSomething()
Theo cch trn ta c th gi methods theo cch Early Bound trong nhiu
interfaces ca mt object m khng cn phi declare mt variable mi.
Tha k t mt ngn ng khc
VB.NET code c compile ra IL (Intermediate Language) managed
code, tc l code s c CLR (Common Language Runtime) chy trong
.NET Framework. Mi managed code, khng cn bit c compiled t
ngn ng no u c th lm vic chung nhau, tc l ta c th to mt
class trong ngn ng ny v dng n trong mt ngn ng khc, k c vic
tha k.
Tht ra hu nh ta lun lun lm vic y khi vit VB.NET. l v phn ln .NET
system library
c vit bng C#, nhng ta dng hay tha k t n thng xuyn trong VB.NET.
To mt VB.NET BaseClass
Trong th d v tha k t mt ngn ng khc, trc ht ta th to mt
Class Library Project trong VB.NET tn vblib v thm vo mt class
n gin tn Parent ging nh sau:
Public Class Parent
Public Sub SayHello()
MsgBox("Hello from Parent Class", MsgBoxStyle.Information, "Parent Class in VB.NET")
End Sub
End Class
Ta s dng Parent lm BaseClass tha k thnh mt SubClass trong
C#.
Cc bi tp Microsoft .NET 108
To mt C# SubClass
Dng File | Add Project thm mt C# Class Library project mi v
t tn n l cslib. Reference vblib bng cch dng Menu command
Project | Add Reference... v chn Tab Projects, click Browse tm
vblib.dll trong vblib\bin subfolder.
Lu l ta va mi reference vblib.dll, ci assembly ca Class Parent, ch ta khng
ng n hay cn VB.NET source code ca Class Parent. Trong C#, ta s tha k
Class Parent qua reference BaseClass trong vblib.dll assembly.
By gi code C# nh sau:
namespace cslib
{
using System.Windows.Forms;
using vblib;
public class cSharpclass : Parent
{
public cSharpclass()
{
MessageBox.Show("Instantiating cSharpclass object, inheriting VB.NET Parent class", "CSharp
Class");
}
}
}
Code C# bn trn c nhiu im tng ng vi VB.NET. Tuy nhin v
C# n t ngn ng lp trnh C v C++ nn n c syntax hi khc mt
cht:
Mi statement trong C# phi chm dt bng du ;
nh du cui hng
Cp du ngoc cong queo { .. } c dng nh du
u v cui ca mt Statement Block thay v dng
End Sub.
Cc bi tp Microsoft .NET 109
Keyword using c dng thay v keyword Imports
trong VB.NET
C# th case sensitive, tc l phn bit ch hoa, ch
thng - th d obj th khc vi Obj.
Constructor method mang cng tn vi class thay v
tn New nh trong VB.NET.
Ta hy th i qua cc dng code. Cu th nht nh ngha namespace cho
source file. Trong C#, mi namespace phi c tuyn b r rng
(explicitly declared) trong mi code module.
namespace cslib
K l hai cu tuyn b ta nhp khu System.Windows.Forms v vblib:
using System.Windows.Forms;
using vblib;
Cu k tuyn b cSharpclass tha k t class Parent, cch dng
du : thay v keyword Inherits:
public class cSharpclass : Parent
Sau cng l Constructor dng chnh tn ca class:
public cSharpclass()
{
MessageBox.Show("Instantiating cSharpclass object, inheriting VB.NET Parent class", "CSharp
Class");
}
cch dng MessageBox.Show ging ht nh trong VB.NET hin
th mt message.
To mt program Client
Dng menu command File | Add Project thm mt VB.NET
Windows Application project mi cho solution. Trong project mi ny ta
dng menu command Project | Add Reference... thm references cho
cslib v vblib. Right-click ln project trong Solution Explorer v chn n
lm Set As Startup Project project ny chy khi ta bm F5.
Cc bi tp Microsoft .NET 110
By gi t mt Button tn BtnStartDemo ln Form v vit code di y
x l Event Click:
Private Sub BtnStartDemo_Click( ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles BtnStartDemo.Click
Dim objCS As New cslib.cSharpclass()
objCS.SayHello()
End Sub
Khi ta chy program v click button StartDemo ta s thy mt dialog cho
bit Constructor ca cSharpclass ang c gi instantiate object
objCS:
Tip theo mt dialog th nh hin th message t Sub SayHello m
objCS tha k t BaseClass Parent:
Tha k hnh nh (Visual Inheritance)
Cc bi tp Microsoft .NET 111
Cho n by gi ta bn qua chc nng OO ca ngn ng VB.NET,
phn ln nhm vo c tnh tha k.
V cc hnh nh (Visual Components) trong VB.NET c implemented
bng ngn ng lp trnh chnh quy ch khng phi dng mt cch thc
khc bit nh trong VB6 (tin tc din t cc hnh nh nm phn u cc
*.frm files), nn VB.NET cng h tr Tha k hnh nh (Visual
Inheritance) cho Windows Forms mt cch t nhin. iu ny c ngha
l sau khi lm xong mt Windows Form vi nhng Textboxes, Labels,
Listboxes ..v.v.. ta c th tha k n ri v thm cc hnh nh khc. Ta
s bn v chi tit v chuyn ny trong tng lai.
Ta cng c th tha k t chnh cc hnh nh. Th d ta c th tha k t
mt Textbox to ra mt class Textbox mi, c thm chc nng nhn
keystrokes theo cch VNI v hin th ch Vit Unicode.
Cng mt nguyn tc tha k ny ca Windows Forms Controls cng p
dng cho Web Forms Controls, tc l ta c th SubClass mt Web
Forms Control, cho thm cc chc nng mi v overriding mt s chc
nng c sn.
Cc bi tp Microsoft .NET 112
Bi 8
Nhng chc nng mi trong giao din ca s ca
VB.NET (phn I)
Xin nhc li l .NET Framework cho ta ba cch user giao din vi
chng trnh p dng, l Windows Forms (c khi c gi tt l
WinForms), Web Forms v Console applications. Ln lt chng ta s
hc qua c ba th ny.
Ngoi ra, k t u thng hai 2002, thy V Nng Hin s vit mt lot
bi ring v ASP.NET. ASP.NET l hu thn ca ASP (Active Server
Pages), ci framework ta lp trnh trn Webserver. Microsoft dng
ASP thay th cgi-Perl (Common Gateway Interface - Practical
Extraction and Report Language), mt ngn ng lp trnh rt thnh
hnh trn cc Unix-based Webserver. Sau ny chnh Microsoft mn
ngi ta port Perl qua WindowsNT.
Mt chng trnh ASP gm c nhiu trang ging nh trang Web (HTML)
nhng bn trong c nhng mnh chng trnh vit bng VBScript hay
JavaScript (tht ra script no cng c, k c PerlScript) nm nhiu
ni. Cc mnh Script ny c th truy cp c s d liu sa i hay ly
d kin ra hin th ti ch y (ni mnh Script nm trong trang ASP)
to trang Web kt qu.
Trong ASP.NET, tt c cc mnh chng trnh Script y c ly ra
ring, chung vi nhau v c vit li di dng ngn ng thun ty
VB.NET hay C#. Phn coding c gi l code behind (code nm
pha sau) v rt ging nh cc Event Handling Sub ta vit trong VB.NET
cho Windows Forms.
Trong tng lai, khi bn n Web Forms ta ch hc tng qut v
ASP.NET v nht l ch dng VB.NET trong cc chng trnh n gin.
S quan trng ca Windows Forms ?
Windows Forms l cch hin th mn nh ti tn hn Win32 bnh thng.
K thut nm pha sau Windows Forms trc y c pht trin cho
Windows Foundation Classes (WFC), dng trong Visual J++. iu
ny ct ngha s gi dn v vng chi ca mt sn phm hy cn tnh
trng Beta.
Cc bi tp Microsoft .NET 113
Khi ta nghe ni n .NET vi nhng ha hn v ng dng trn Internet
nh Web Forms v Web Services, rt d cho ta tng rng Microsoft phi
cung cp Windows Forms l cc chng cho n trn vn mn hng.
Tht ra, Windows Forms l mt phn ca cc base classes ca .NET
Framework. Ci Namespace dng cho n l System.Windows.Forms,
mt Namespace cha rt nhiu th n i hu nh chng ta s khng
cn phi dng trc tip cc Windows API v ho (Graphics v
Drawings) nh trong VB6 na.
Nhu cu c nhng p dng pha khch (client-based application) phong
ph (rich), linh ng (flexible) v nhanh chng (responsive) s vn cn
. Hin nay, trnh ph tn v ci t (deployment) cc chng trnh,
ngi ta bt u c khuynh hng t cc chng trnh chy trn
Webserver, ri cho user s dng chng qua WebBrowser. Ngoi cng
chng th dng Internet, trong hng xng th dng Intranet (Intranet l
Internet chy trn Local Area Network - mng a phng, khng lin lc
g vi bn ngoi), tuy nhin giao din trn Web khng phong ph hay
nhanh nh trn desktop v d nhin cng tc lp trnh i hi mt thi
gian pht trin lu hn.
V .NET Framework cha y mi th vin cn thit cho chng
trnh, nn mt khi ci t .NET Framework trn my khch ri ta ch
cn XCopy n nhng folders cn thit c cha cc tp (files) chng
trnh v d kin l . Thc hin vic ny trn mng a phng (Local
Area Network) rt d v nhanh, thm ch ta c th t ng ha cng tc
copy ny.
Trong m hnh lp trnh nhiu tng (multi-tier programming model) m
ta gi l Windows DNA (Distributed Network Application), qu trnh
x l mt cng tc c chia ra lm nhiu giai on nh:
1. Kim chng cc con s user mi in vo cc forms
ti my khch (user interface)
2. Tnh ton (business logic)
3. Truy cp c s d liu (database access)
V mi giai on ni trn c th nm trn mt computer khc nhau. Nu
dng Internet th giai on 1 ni trn s chy trong WebBrowser bng
trang Web c cha JavaScript routines kim chng cc con s user
Cc bi tp Microsoft .NET 114
mi nh vo. Cn cc giai on kia c th chy trn WebServer. D
nhin giai on 3 phi chy trn WebServer, ni cha c s d kin.
.NET cho php ta lp trnh giai on 1 chy trong Windows Forms.
Cn cc giai on kia c th y nguyn.
Nh th, gi d nh ta c mt h thng t hng, ta c th cho cc
telephone operators dng desktop (Winforms) application vi mt giao
din c ti u ha, chy tht nhanh phc v nhng ngi t hng
bng in thoi. Trong khi khch hng cng c th t hng qua
Internet WebBrowser nh bnh thng. C hai nhm users ny d c giao
din khc nhau nhng u xi chung cc tng business logic v database
access.
y l mt u im rt quan trng ca .NET m t ai ch . Nu thit k
kho, ta c th lp trnh dng chung hu ht phn mm trn desktop,
distributed (phn tn), Internet v Mobile (Mobile phone, Pocket-PC).
Nhng im cn bn ca Windows Forms ?
Trong cc bi hc v th d trc y ta ni qua, by gi ta tm tc
nhng im cn bn ca Windows Forms:
Mt Windows Form tht s l mt class. Trong .NET
khng c t c bit nh "form module" dng cho
n.
V mt form l mt class nn ta khng th load n m
khng ni thng thng ra. Tc l trong VB6 nu ta
Show hay dng n mt Form th n t ng c
loaded. Chng nhng th thi, ci class Form2 c
dng nh mt variable Form2 lun, tc l by default
ta c mt Object tn Form2. Trong .NET ta phi khai
bo (declare) mt variable tn myForm2 chng hn ri
instantiate form y nh mt Object ca Form2 trc
khi dng n.
Tt c mi form u tha k t class
System.Windows.Forms.Form.
Ging nh tt c cc classes trong .NET Framework,
Windows Forms c constructors v destructors.
Constructor ca form tn l Sub New, i khi ging
Cc bi tp Microsoft .NET 115
nh Sub Form_Load trong VB6. Destructor ca form
tn l Sub Dispose, i khi ging nh Sub
Form_Unload trong VB6.
Ci visual forms designer ca VS.NET nht rt nhiu
code instantiate form v t cc controls vo form.
l code m ng l ta phi t vit nu ta dng
notepad lp trnh. Phn code ny thay th ci phn
nm u tp .frm ca VB6 din t cc visual
components ca form. Mi ln ta thm bt cc
controls hay thay th cc properties ca controls trn
form th code generated cho form c thay i theo.
Do bn nn trnh sa i code y, tr khi bit chc
mnh ang lm g, hay l bn lm mt phin bn trc
khi thay i nu l kt th restore code c.
Event c x l bng cch linh ng hn. Cc events
cha nhiu tin tc hn. Mt Event c th c x l
bi nhiu controls cng mt lc v mi control c mt
cch x l khc nhau. Ngc li, nhiu Events khc
nhau c th c x l bng mt Event Handler duy
nht.
Bn to mt chng trnh Windows Forms bng cch dng IDE menu
command File | New | Project.. hin th giao thoi New Project v
chn Template Windows Application.
Cc bi tp Microsoft .NET 116
Trong th d ny, khi bn click nt OK th mt subfolder tn (Name:)
WindowsApplication4 s c to ra trong folder (Location:)
E:\NET\HongDevelopment\LessonPreparation cha cc tp ca
Project. Sau ny, khi bn build, tc l compile chng trnh, th kt qu
s l mt tp .exe cha trong folder
E:\NET\HongDevelopment\LessonPreparation\WindowsApplication
4\bin.
D nhin trc khi click nt OK bn c th sa Name: hay Location: ty
. Ngoi ra, v bn chn Windows Application, nn project ca bn t
ng c reference n .NET component System.Windows.Forms.dll.
xem lt qua namespace System.Windows.Forms, bn hy th xc
tin to ci project WindowApplication4 ny. K bn chy Object
Browser bng cch click hnh tam gic nh ca Class View icon ri chn
Object Browser:
Cc bi tp Microsoft .NET 117
Trong Object Browser, expand ci System.Windows.Forms tree xem
nhng types c nh ngha bn trong v cc class members ca Form:
Kin trc (Architecture) ca Windows Forms ?
Cc bi tp Microsoft .NET 118
Nu bn xem gia ph ca form, bn s thy t ph (i th nht) n l class Object,
cn form l con chu i th by. Di y l ci cy ca gia ph form v mt t ch
thch:
Th bc cc classes Ch thch
Object
ng t trong .NET, superclass cao nht t sanh ra
con chu.
MarshalByRefObject
Cung cp cc code cn thit qun l cuc i ca
objects.
Component
Cung cp s gy dng cn bn ca IComponent
interface v cho php cc chng trnh khc nhau
dng chung mt object
Control
y l base class ca mi component dng hin
th. N h tr nhng kh nng lin h n vc dng
v cng tc hin th t Show, BringtoFront, Font,
Color cho n Dock, Anchor. Ngoi ra n cn cung
cp cc Events ca keyboard, mouse v c method
WndProc cho ta truy cp cc thng ip ca
Windows.
ScrollableControl
Cung cp chc nng t ng cun khi c cha bn
trong mt control cn thm ch hin th.
ContainerControl Cho php mt component cha cc controls khc.
Form Ca s chnh ca mt chng trnh.
Cc chc nng mi ca Windows Forms
Nhng Controls tn hnh c cha ring
Mt thay i rt tt trong .NET t VB6 l nhng controls khng hin th
lc chy th khi thit k chng c cha trong mt ci mm ring pha
di. Th d nh trong hnh di y ta c Timer, Tooltip, Menus v cc
Dialogs c cho nm trong mt component Tray.
Mun thay i properties ca Control no, ta ch cn chn n ri right
click v chn Properties.
Chn Startup Form
Cc bi tp Microsoft .NET 119
ch nh StartUp Form ca chng trnh, bn cn phi m ca s Properties ca
Project nh vo Startup Object. Bn c th lm iu y bng cch dng IDE
menu command Project | Properties hay right click tn ca Project trong Solution
Explorer ri chn Properties.
V tr ban u
Nhiu lc ta mun form hin ra ngay gia mn nh khi chng trnh khi
ng. VB.NET c th lm vic y t ng nu bn set property
StartPosition ca n thnh CenterScreen. Cc v tr khi u bn c th
set c lit k di y:
Tr s V tr khi u Kt qu
Manual
Hin th form v tr theo gi tr ca property Location
ca form
CenterScreen Hin th form ngay gia mn nh
CenterParent Hin th form ngay gia form ch (owner) ca n
WindowsDefaultLocation Hin th form v tr default ca ca s
WindowsDefaultBounds
Hin th form v tr default ca ca s, vi kch thc
default ca ca s
Borders ca Form
Cc bi tp Microsoft .NET 120
Thay i property FormBorderStyle s nh hng nhng g user c th
thay i hay dng v MaximizeBox, MinimizeBox, SizeGripStyle (my
ci gch cho gc di phi ca ca s) v HelpButton.
Lun lun nm trn ht
Mt s chng trnh c kh nng lun lun nm trn ht, ngay c khi n
khng c focus. thc hin iu ny trong VB6 ta phi gi API. Trong
VB.NET, forms c mt property mi tn l TopMost. Ch cn set
TopMost ca mt form thnh True th n lun lun nm trn ht.
Owned Forms (Forms c ch)
Khi mt form c ch, n c minimized v closed theo form ch ca n.
Owned forms, i khi cn c gi l forms n l, lun lun nm ln trn
form ch ca n. Du vy, n khng cn tr form ch nhn focus.
Ta dng method AddOwnedForm ca form ch cho thm owned
form vo collection of OwnedForms ca n nh sau:
Private Sub Form1_Load( ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
MyBase.Load
Dim myForm2 As New Form2()
myForm2.Show()
Me.AddOwnedForm(myForm2)
End Sub
Form ch c th truy cp collection ca cc forms n l qua property
OwnedForms. Di y l code loop qua cc forms n l ca mt
form:
Private Sub BtnListOwnedForms_Click( ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles BtnListOwnedForms.Click
Dim OwnedForm As Form
For Each OwnedForm In Me.OwnedForms
Console.Write(OwnedForm.Text)
Next
End Sub
Cc bi tp Microsoft .NET 121
Form ch c th ct b (remove) mt form n l bng cch dng method
RemoveOwnedForm nh:
Me.RemoveOwnedForm(myForm2)
Khi mt form khng cn l n l na, n khng hn b unloaded, ch tr
thnh mt form t do (khng cn lin h vi form ch na) thi.
Ch s khc bit gia form n l v TopMost form l form n l ch
nm trn form ch n, trong khi TopMost form nm trn tt c mi forms
khc. TopMost form cng khng b minimized hay closed khi mt form
no khc ca chng trnh b minimized hay closed.
Khng phi mi controls u b kho (locked)
Trong Vb6, ta c option Lock Controls trong Format menu. Khi ta chn
Option ny cho mt form, tt c controls u b kha, ngay c nhng
controls mi c vo mt form sau ny.
Trong VB.NET, ta cng c option Lock Control trong Format menu hay
khi ta right click mt nhm controls c chn trn form. Nhng thao
tc kha ny ch hiu lc i vi cc controls c sn trn form m thi.
Mt control mi c t ln form sau s khng b kha. iu ny
cho php ta kha nhng controls c ng v tr, ri tip tc sp
t cc controls mi m khng ngi v tnh lm di chuyn v tr cc
controls c.
m (Opacity) ca Form
C mt property mi ca form rt th v dng, d rng s ch li hay
mc ch ca p dng khng r rng. l ta c th thay i m ca
mt form. Ta c th lm cho n trong sut khi set property Opacity ca
form bng 0, hay cho n m m nh ma nu tr s ca Opacity t hn 1.
Bn hy th nh code di y vo mt form cho Button1 chng hn,
ri chy chng trnh v click Button1 y:
Private Sub Button1_Click( ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
Button1.Click
Dim i As Double
For i = 0 To 1 Step 0.01
' Opacity c tr s t 0 (trong sut) n 1 (m t)
Cc bi tp Microsoft .NET 122
Me.Opacity = i
Next
End Sub
Form properties cho Cancel Button v Default Button
Trong VB6, ta c th set mt button n nh c clicked khi tht ra
user bm phm Esc. Ta thc hin iu ny bng cch set property
Cancel ca button y thnh True. N c gi l Cancel button.
Tng t nh th, nu ta set property Default ca mt button thnh
True, n c gi l Default button, khi user bm phm Enter Default
button coi nh c clicked.
Trong VB.NET ta cng c th dng cc chc nng y, nhng by gi ta
khng ng g n property no ca cc buttons, m li set cc
properties CancelButton v AcceptButton ca chnh form.
Khi ta click bn phi ca property AcceptButton trong ca s Properties
th danh sch cc buttons c sn trn form c lit k ra ta chn nh
di y:
Cc bi tp Microsoft .NET 123
Ngoi ra ta cng c th chn cc CancelButton v AcceptButton lc ang
chy chng trnh, nht l khi ta mun b nhim cc cng tc ny cho
nhng buttons khc v form ang lm vic trong mt trng thi khc nh
trong code th d di y:
Me.CancelButton = BtnCancel2
Me.AcceptButton = BtnAccept2
Cc bi tp Microsoft .NET 124
Bi 9
Nhng chc nng mi trong giao din ca s ca
VB.NET (phn II)
S khc bit trong cc Hp Giao Thoi (Dialog Boxes)
Trong VB6, cc hp giao thoi tht ra l nhng form bnh thng nhng
c hin th vi parameter vbModal, tc l trong Modal mode. iu ny
khn cho hp giao thoi tr nn form tch cc (active form) duy nht
trong chng trnh cho n khi n i khut.
Mt hp giao thoi cn mt phng tin lin lc vi form gi n
(calling form). Trong VB6, ta gii quyt vn ny bng cch ch ra mt
property tm gi l Action. Ta dng Read-only property Action nh sau
trong mt hp giao thoi c hai buttons, OK v Cancel:
' VB6 code used for Dialog Boxes
Public Enum dialogAction
actionOK = 1
actionCancel = 2
End Enum
Dim mAction As dialogAction
Public Property Get Action() As dialogAction
Action = mAction
End Property
Private Sub cmdOK_Click()
' Get here when user click the OK button
mAction = actionOK
' Hide the Dialog Box to return control to calling form
Me.Hide
End Sub
Cc bi tp Microsoft .NET 125
Private Sub cmdCancel_Click()
' Get here when user click the Cancel button
mAction = actionCancel
' Hide the Dialog Box to return control to calling form
Me.Hide
End Sub
Ch ta dng Enumerated type dialogAction. N c hai tr s:
actionOK v actionCancel. Property Action thuc loi enumerated type
ny. Khi user click mt button, ta set tr s cho local variable mAction ri
Hide ci dialog box. Ci Giao thoi phi c du i (hidden) nhng
khng unloaded, v ci calling form cn phi truy cp dialog box c
tr s ca property Action bit user va mi click button no.
Gi d ta t tn cho hp giao thoi l frmDialog. gi mt hp
giao thoi t mt form khc trong VB6 ta c th code nh sau:
Dim Dialog As frmDialog
Set Dialog = New frmDialog ' Instantiate a Dialog Box
' Show dialog box in Modal mode
Dialog.Show vbModal
Nhng bao nhiu ch l hin th hp giao thoi thi. Sau khi hp giao
thoi Hide ri ta cn phi truy cp n c tr s ca property
Action. Do ta cn phi vit thm codes cho y sau y:
Dim Dialog As frmDialog
Set Dialog = New frmDialog ' Instantiate a Dialog Box
' Show dialog box in Modal mode
Dialog.Show vbModal
' Get here after the dialog box has hidden, but still loaded
' Now process the Action
Select Case Dialog.Action
Case actionOK
Cc bi tp Microsoft .NET 126
' code goes here for normal processing
Case actionCancel
' code goes here for user canceling
End Select
Unload Dialog ' Now we can unload the dialog box
C hai s thay i quan trng trong VB.NET, l dng ShowDialog v
DialogResult.
ShowDialog thay v Show vbModal
Argument vbModal khng c h tr trong VB.NET. Thay vo , mt
form c th dng method ShowDialog. Di y l s so snh ca
coding trong VB6 v VB.NET.
VB6 code:
Dim Dialog As frmDialog
Set Dialog = New frmDialog ' Instantiate a Dialog Box
' Show dialog box in Modal mode
Dialog.Show vbModal
VB.NET code:
Dim Dialog As New frmDialog()
' Show dialog box in Modal mode
Dialog.ShowDialog
l trong VB.NET hng code u ta c th kt hp hai chuyn khai
bo v instantiate form mi trong mt statement. Hng code cui cho
thy s thay i t Show vbModal qua ShowDialog.
DialogResult
Trong VB.NET, khi mt form khi th bng method ShowDialog, n
d b sn mt property tn l DialogResult calling form c th truy
cp.
DialogResult c th mang mt trong nhng tr s enumerated sau y:
DialogResult.Abort
Cc bi tp Microsoft .NET 127
DialogResult.Cancel
DialogResult.Ignore
DialogResult.No
DialogResult.None
DialogResult.OK
DialogResult.Retry
DialogResult.Yes
C im rt tin l khi DialogResult c set cho mt tr s th dialog
c du i (hidden) mt cch t ng.
Cch n gin nht set tr s cho DialogResult l assign mt tr s cho
property DialogResult ca mt button. Khi user click button y th
DialogResult ca hp giao thoi ly tr s ca property DialogResult ca
button v hp giao thoi Hide.
biu din ShowDialog trong VB.NET, km theo y l m ngun ca
mt th d. Trong th d ny ta to mt form tn frmDialog c hai button
tn OK v Cancel. Ta set property DialogResult ca button OK thnh OK
Cc bi tp Microsoft .NET 128
v property DialogResult ca button Cancel thnh Cancel. Form
frmDialog hon ton khng c mt hng code no c.
Form chnh ca chng trnh, Form1, ch c mt button tn
BtnShowDialog vi code cho Event Click nh di y:
Private Sub BtnShowDialog_Click( ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles BtnShowDialog.Click
' Declare and instantiate a Dialog Box
Dim Dialog As New frmDialog()
' Show the Dialog Box in Modal mode
Dialog.ShowDialog()
' get here after user has clicked a button and the Dialog box has hidden
' Process the DialogResult
Select Case Dialog.DialogResult
Case DialogResult.OK
MsgBox("User clicked OK, se please go ahead")
Case DialogResult.Cancel
MsgBox("Sorry, but User clicked Cancel")
End Select
Dialog = Nothing ' Dispose the Dialog Box
End Sub
Bn c th chy chng trnh ri click button ShowDialog. Khi Dialog
box hin th, th click mt trong hai buttons trn y.
So snh vi VB6, ta thy dng Dialog Box trong VB.NET n gin v t
nhin hn.
Nu khng dng Property DialogResult ca mt button trong Dialog Box
tr v kt qu DialogResult, ta cng c th dng code trong Dialog
form nh sau:
Me.DialogResult = DialogResult.Retry
Cc bi tp Microsoft .NET 129
Hng code trn set DialogResult ca Dialog form thnh
DialogResult.Retry v km theo phn ng ph l Hide Dialog Box.
Calling form s truy cp c kt qu DialogResult.Retry ny.
S khc bit v sp t v tr cho Forms v Controls
VB.NET c nhng chc nng v positioning v layout tng t nh trong
VB6, nhng cch thc thi hi khc.
Property Location
Thay vo cc properties Left v Top trong VB6, forms v controls trong
VB.NET c property Location. Property Location nhn v tr v mt
structure tn Point, c ta X v Y tng ng vi Left v Top m ta
dng trc y.
Structure point c dng trong nhiu p dng v ha trong GDI+
(Graphic Devices Interface plus) ca .NET.
Tht ra, trong code ta vn cn dng Top v Left c nh xa. Nhng
Top v Left khng hin ra trong ca s Properties ca forms hay controls.
ch nh mt v tr mi cho form, ta c th code nh sau:
Me.Location = (New Point(200, 100))
Property Size
Property Size trong VB.NET c cng mt nim nh property Location,
c iu n tng xng vi Width v Height. Property Size nhn v tr v
mt structure tn Size, c chiu cao v chiu rng p dng cng mt
lc thay v tun t tng chiu. Ging nh Left v Top, trong code ta vn
cn dng Width v Height c nh xa. Nhng Width v Height khng
hin ra trong ca s Properties ca forms hay controls. thay i Size
ca mt form, ta c th code nh sau:
Me.Size = (New Size(300, 400))
ReSize nhiu controls
VS.NET cho ta mt chc nng mi l Resize nhiu controls cng mt
lc. Trc ht bn Select nhiu controls bng cch drag mt dy thun
(rubber band) bao quanh chng hay n nt Ctrl trong lc click cc
Cc bi tp Microsoft .NET 130
controls. K , tp trung vic resize vo mt control, cc controls kia
cng c resized theo.
Cc features thit k chung cho cc Controls
Tab Order ca cc Controls
Sp t th t trong Tab ca cc controls (Tab Order) trn mt form i
khi rt phin phc trong VB6. VS.NET cho ta mt feature rt tin dng
lm vic ny. khi ng feature y, ta dng IDE menu command
View | Tab Order. N s hin th mt con s nh gc trn tri ca mi
control, cho thy tr s Tab Index ca mi control. By gi ta ch cn
click ln tng control mt theo th t m ta mun.
Di y l screenshot ca mt form sau khi user ch nh Tab Order cho
cc controls. Mun ra khi Tab Order mode, ta bm menu command
View | Tab Order mt ln na.
Ghi ch:Trong VB.NET nhiu controls c th c cng mt Tab Index.
Trong trng hp y, th t v Tab ca chng c quyt nh da vo
z-order. Control c z-order cao nht s nhn focus trc nht trong
nhm. Z-order ca mt control c th c thay i bng cch right click
control ri chn Bring to Front.
Control Arrays
Khi nghe ni VB.NET khng h tr Control Arrays chc bn bun nm
pht. C hai l do ti sao bn cn Control Arrays:
1. Dng cng mt Event handler (th d nh Sub
BtnBrowse_Click) x l Event t nhiu Controls
tng t.
Cc bi tp Microsoft .NET 131
2. dynamically to thm Controls trong form lc
ang chy program (at runtime).
May thay, VB.NET cung cp cho ta mt phng tin khc khi phi
thua thit. VB.NET cho php ta linh ng b nhim cc methods x l
Events ca cc controls. im th nht bn s ch l bn khng th
dng cng mt tn cho nhiu controls na. Property Index b khai t.
Trong VB.NET bn c th dng mt Event handler duy nht x l
Events n t cc controls tng t. Trc y ta da vo Index bit
Event pht xut t control no. By gi bn da vo parameter Sender.
minh ha im ny, ta s vit mt chng trnh c hai buttons,
Button1 v Button2, nm trn form chnh. Double click Button1 vit
code x l Event Button1.Click. Mun dng cng mt Event Sub ny
x l lun Event Click n t Button2, bn ch cn thm ch
Button2.Click vo cui ci Handles List ca Sub Button1_Click.
cho c v tng qut ta rename Sub Button1_Click thnh Sub
Button_Click.
By gi ta vit vi dng code n gin hin th cho bit Event Click
n t Button no:
' Note that we change the name of the Sub from Button1_Click to Button_Click to
' make it more general, since we're going to use this same Sub to handle Click
' Events originated from many different Buttons
' Also note that we add the word Button2.Click to the end of Sub Button_Click declaration
Private Sub Button_Click( ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles Button1.Click, Button2.Click
Dim btnClicked As Button
' Type cast sender to Button
btnClicked = CType(sender, Button)
' Show what button was clicked
MessageBox.Show("You clicked """ & btnClicked.Text & """")
End Sub
Cc bi tp Microsoft .NET 132
Th chy chng trnh v click Button2, bn s thy hnh di y:
biu din chc nng qun l Event Handling at runtime, ta s t mt
button tn BtnAddNewButton vo form n dynamically add mt
button th ba tn Button3. Ta mun button ny cng s dng Sub
Button_Click x l Event Click ca n. V khng th nh thm ch
Button3.Click vo cui cu Sub Button_Click nh trc y ta lm
vi Button2.Click, nn at runtime ta s dng statement:
' Tell system to use Button_Click as Event Handler for the Event Button3.Click
AddHandler newButton.Click, AddressOf Me.Button_Click
M ngun y ca Sub BtnAddNewButton_Click c lit k di
y:
Private Sub BtnAddNewButton_Click( ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles BtnAddNewButton.Click
' Declare and instantiate a Button
Dim newButton As New Button()
' Set it up on the form
With newButton
.Text = "Button3" ' Text of this new button
.Location = New Point(230, 120) ' define its location on the form
.Size = New Size(88, 40) ' define its size
End With
' Add the new button to the form's collection of controls
Me.Controls.Add(newButton)
Cc bi tp Microsoft .NET 133
' Tell system to use Button_Click as Event Handler for the Event Button3.Click
AddHandler newButton.Click, AddressOf Me.Button_Click
End Sub
Khi user click BtnAddNewButton, Button3 vi Size(88,40) s c to ra
v t Location(230,120) trn form. K n chng trnh thc hin hai
chuyn quan trng: Add button mi ny vo collection of controls ca
form v ng k (register) vic dng Sub Button_Click lm Event
Handler ca Event Click ca n.
Lm xong my chuyn ny ri, bn chy chng trnh, click
AddNewButton thm Button3 vo form, k click Button3, bn s
thy hnh di y:
Cc bi tp Microsoft .NET 134
Bi 10
Nhng chc nng mi trong giao din ca s ca
VB.NET (phn III)
T ng Resize v nh ch (positioning)
Nhng chng trnh ng dng chuyn nghip ta mua ngoi ch dng
thng thng c c tnh resize cc controls hay nh v tr ca cc
controls trn form mt cch t ng. Nu bao gi bn th thm cc
chc nng y cho mt chng trnh p dng vit bng VB6 ca mnh, bn
s thng cm rng coi vy ch khng phi l chuyn nh.
Tng tng l ta phi ghi nh v tr v kch thc ca mi control trn
form mi ln user resizes form th ta phi theo resize v nh v tr
ca control. Trong lc thit k ta phi cho user mt phng tin ch
nh rng h mun mt control c x nh th no khi form resize.
cha tin tc y hoc ta dng property Tag ca control hoc ta dng
registry. Ch vic c ra, vit vo cp nht ho cc tin tc cng mt,
cha ni n chuyn tnh ton resize v nh v tr ca control. Do ,
nhiu khi lm bing ta dng i mt third party ActiveX gip ta lm
cc chuyn y.
.NET cho ta thm cc properties Anchor v Dock cho mi control.
Ngoi ra .NET cn cung cp control Splitter cho php ta nm mt
thanh phn hai ko qua, ko li hay ko ln, ko xung ty thch, m
rng thm mt bn trong khi bn kia b thu hp.
Ci p dng ca Splitter thng dng nht l trong Windows Explorer.
Trong ta c hai phn: bn tri l mt Treeview cha ci cy ca disk
drives v file folders, bn phi l mt Listview cha icons hay chi tit ca
cc folder v files. Mun xem Treeview nhiu hn, ta nm thanh phn hai
gia ko qua bn phi mt cht.
Cc bi tp Microsoft .NET 135
Anchoring (b neo)
Khi con tu b neo l n . D con nc chy th no, con tu vn
nm yn mt ch v n c ct vo ci neo. Control trong .NET c
property Anchor ta ch nh n c buc vo gc no ca form:
Left, Right, Bottom hay Top.
Trong lc thit k, sau khi select ci control (th d Button1), ta vo ca
s Properties v click hnh tam gic nh bn phi property Anchor. Mt
hnh vung vi bn thanh rp li ging hnh ch thp mu trng s hin
ra. Mi thanh tng trng cho mt gc m ta c th ch nh ct
control vo form. Khi ta click mt thanh, n s i mu thnh xm m,
v mt ch tng ng vi thanh y sau ny s hin th trong textbox area
ca combobox Anchor.
Th d ta click vo thanh di v hai thanh hai bn, ta s c Bottom,
Left, Right nh trong hnh di y:
Cc bi tp Microsoft .NET 136
Khi Button1 c Anchor l Bottom, Right th mi khi gc phi di ca
form di chuyn v resize, Button1 c chy theo gc y:
Nu Button1 c Anchor l Left, Right, Bottom th khi form resizes cho
ln ra, Button1 c gi khong cch t n n ba cnh Left, Right, Bottom
ca form khng i. Do n phi n rng ra nh trong hnh di y:
Nu Button1 c Anchor l Top,Bottom,Left, Right th khi form resizes,
Button1 c gi khong cch t n n bn cnh Left, Right, Top, Bottom
Cc bi tp Microsoft .NET 137
ca form khng i. Do n phi n rng hay thu nh c chiu cao ln
chiu rng nh trong hnh di y:
V property Anchor c hiu lc lp tc ngay trong lc ta thit k, nn nu
bn resize form trong lc thit k, cc control c Anchor property set
cng resize v di chuyn theo. C th bn khng mun chuyn xy ra,
nn tt nht l set property Anchor ca cc control sau khi thit k form
xong ht ri.
Docking (gn vo)
Khi ta Dock mt control vo mt cnh ca form c ngha l ta dn dnh
n vo cnh . p dng ta thng thy nht ca Docking l ToolBar v
StatusBar. ToolBar th dock vo pha trn ca form, cm StatusBar th
dock vo pha di ca mt form. Chng dn ra chim t tri qua phi
ca form, user khng th ch nh chiu rng ca chng. Khi form c
resized th ToolBar v StatusBar cng dn ra hay co vo theo chiu rng
ca form.
Property Dock ca control trong .NET cng ging ging nh property
Align ca control trong VB6 StatusBar.
Ta ch c th dn mt control vo mt trong bn cnh ca form, ch
khng c chuyn bt c hai, ba tay nh trng hp Anchor c th neo vo
Left, Right, Bottom cng mt lc. Tuy nhin, property Dock c tr s Fill
ni control chim ht bn trong phn cn li ca container ca n.
Trong lc thit k, sau khi select ci control (th d Label1), ta vo ca s
Properties v click hnh tam gic nh bn phi property Dock. Mt hnh
Cc bi tp Microsoft .NET 138
vung nhiu thanh mu xm s hin ra. Mi thanh tng trng cho mt
cnh m ta c th ch nh dn control vo form (Top, Bottom, Left
hay Right), ci hnh vung gia tng trng cho tr s Fill, v thanh
di cht c ch None cho php ta xa khng chn tr s Dock no c..
Khi ta click mt thanh, tr s Docking tng ng s hin th trong textbox
area ca combobox Dock.
Gi s ta set Property TextAlign ca Label l MiddleCenter bng cch
chn ci thanh xm nm ngay gia trong s 9 thanh tng trng cho cc
v tr ca Text c th nm trong Label1 nh trong hnh di y:
Cc bi tp Microsoft .NET 139
Khi chy chng trnh v resize form cho ln ra, ta s thy Label1 dn ra
hai bn, nhng khng h tng b cao, v Text ca Label1 lun lun nm
gia.
Nu bn tm cch dock nhiu controls vo cng mt cnh ca form th
VB.NET phi quyt nh control no nm st cnh y nht. Qui c v
th t l ngc li vi th t trong z-order. Tc l trong z-order, control
no nm di nht th li c dock trc nht vo cnh ca form. Do
, nu bn dock hai controls vo mt cnh, v mun ci control nm xa
cnh c dock trc nht (tc l st cnh nht) th right click control y
v chn Send To Back.
Nu bn mun cha mt khong trng gia control v cnh ca container
th set Property DockPadding ca container. T trc n gi ta dng
form i din container cha controls. Tht ra container cng c th l
mt Panel. Bn c th set Property DockPadding ca cc cnh ca
Cc bi tp Microsoft .NET 140
container khc nhau bng cch click du + bn tri ch DockPadding
trong ca s Properties m ra cc chi tit nh trong hnh di y:
Bn c th set tt c Property DockPadding cng mt tr s bng cch
dng All setting.
Control Splitter
By gi bn hiu r cc c tnh, s khc bit v cch dng hai
properties Anchor v Dock ca control, sau y ta s p dng kin thc
y vo vic thit k dng Splitter trong mt form. Nu cn mi vi
Splitter bn s d b bc mnh khi dng n. Do , bn hy th lm theo
cc bc sau y:
1. To mt Application mi, t mt Panel ln pha tri
ca form chnh n chm bn tri ca form bng
cch set property Dock ca n thnh Left. Ta gi
Panel y l Panel1.
2. t mt Splitter ln form (nh trnh t n ln Panel1
v Panel cng l mt loi container nn c th cha
Splitter c). Splitter s t ng dock Left vo form
tc l nm bn phi Panel1. Chn property
BoderStyle ca Splitter1 lm FixedSingle cho d
thy.
3. t mt button ln Panel1 v set property Anchor ca
n thnh Top, Left, Right. By gi form s ging nh
di y:
Cc bi tp Microsoft .NET 141
4. K , t mt Panel ln bn phi ca form, gi l
Panel2, v set property Dock n thnh Fill. C ngha
l ta mun Panel2 chim ht phn cn li bn phi ca
form.
5. Thm vo trong Panel2 ny mt Button, gi l
Button2, v set property Anchor ca n thnh Top,
Left, Right.
Khi chy chng trnh, mi ln bn nm Splitter ko qua phi th Button1
dn ra v Button2 co li:
Cc bi tp Microsoft .NET 142
Ngc li, nu bn nm Splitter ko qua tri th Button1 co ra v Button2
dn li:
Trong th d ny ta yn chiu rng ca Splitter, nhng bnh thng ta
lm cho n hp hn. Nu Splitter hp th kh thy, do bn c th cho
n mt mu rc trong lc thit k d thy. Khi thit k xong ht ri,
bn i n li thnh mt mu du hn.
Nu by gi bn mun chia Panel2 thnh hai phn, ngn cch bi mt
Horizontal Splitter th sao? Ta c xem Panel2 nh mt form vy, tc l c
Cc bi tp Microsoft .NET 143
hai u l containers, loi control c th ng nhiu controls, v lp li
cc bc sau:
1. t mt Panel ln pha trn ca Panel2, gi n l
Panel3 v set property Dock ca n thnh Top.
2. t mt Splitter ln Panel2 (nh trnh t n ln
Panel3), gi n l Splitter2 v set property Dock ca
n cng thnh Top. Resize Splitter2 cho n dp li v
i property Backcolor thnh ra ControlDark cho
d thy.
3. t mt Panel ln pha di ca Panel2, gi n l
Panel4 v di Button2 t Panel2 qua Panel4 bng cch
Cut and Paste.
4. Set property Dock ca Panel4 thnh Fill.
By gi hy chy chng trnh v nm ko Splitter2 ln xung.
Tm li, mun dng control Splitter trong mt form hay panel ta t mt
PanelX vi Docking Left hay Top ln trc, k t mt Splitter vi
cng loi Docking vi PanelX, ri t PanelY vi Docking Fill.
Cc bi tp Microsoft .NET 144
Bi 11
Nhng chc nng mi trong giao din ca s ca
VB.NET (phn IV)
Cc control Providers
Trong Windows Forms c mt gia nh controls mi m ta ch c th
dng khi chng i chung vi cc controls khc trn cng mt form.
Chng c gi l Provider Controls v c c tnh l khin cho cc
property mi hin ra trong cc controls khc.
Provider Controls khng hin th trn form lc chy program. Do
chng nm ring trong Component Tray lc ta thit k. Hin gi c 3
Provider Controls : HelpProvider, ToolTip v ErrorProvider. C ba
u lm vic mt cch tng t nhau.
Controls HelpProvider v ToolTip
Trong VB6, cc controls c property HelpContextID ta ch nh khi
user bm nt F1 th chng trnh s hin th Help ng trang c tr s
HelpContextID trong Help file. Cn ToolTip l mt Textstring property
ca mi control. Ta ch cn dng ca s Properties cho vo ToolTip
text ca mt control l trong lc chy chng trnh, khi no ta mouse
cursor nm ln control l chng trnh s hin th ToolTip text.
Hai th y khng cn dng trong Windows Forms na. Thay vo , ta
phi t cc Provider Controls ln form thc hin cc cng tc tng
ng.
Control HelpProvider cho php cc controls khc ch nh context
sensitive help (tr gip trong tnh hung ng thi) hin th khi user
bm nt F1. Khi mt control HelpProvider (gi l HelProvider1 by
default) c thm vo mt form, th mi controls trn form u s c
thm cc properties di y, chng s hin th trong ca s Properties
sau khi ta chn mt control.
Property p dng
Cc bi tp Microsoft .NET 145
HelpString on
HelpProvider1
Khi control c focus, user bm nt F1 s popup Tooltip
HelpString cho control
HelpTopic on
HelpProvider1
Cung cp mt Topic cho control dng trong Help file cho
context-sensitive help. Control HelpProvider1 c mt property
ta ch nh dng Help file no
ShowHelp on
HelpProvider1
Xc nh l control HelpProvider c Active cho control ny
khng
Mt khi property HelpString c cho mt Textstring th trong lc
control nhn c focus, nu user bm nt F1 mt Tooltip s hin th
Textstring y. HelpProvider c mt property dn n mt Help file,
hoc l HTMLHelp file, hoc l Win32Help file, v tr s trong property
HelpTopic s ch dn n topic y trong Help file.
Trong lc chng trnh chy, ta cng c th thay i tr s HelpString ca
Textbox1 nh sau:
HelpProvider1.SetHelpString(Textbox1, "Mt HelpString mi c dng ti y.")
Control ToolTip cng hot ng tng t, nhng n gin hn. N ch
cho thm mt property mi tn ToolTip on ToolTip1 vo mi control,
gi d tn ca ToopTip provider l ToolTip1. Property ny lm vic y ht
nh ToolTipText trong VB6.
Trong lc chng trnh chy, ta cng c th set cho property Tooltip ca
Textbox txtName mt tr s Textstring nh sau:
ToolTip1.SetToolTip(txtName, "Xin vui lng nh tn bn vo y")
Control ErrorProvider
Thng thng sau khi user in xong cc d kin vo mt form th s
click mt button OK hay Submit chng hn. trnh trng hp cp
nht data ca mt record vi nhng d kin bt hp l, ta thng kim tra
li d kin nm trong tng Textbox trn form v hin th mt thng ip
nhc nh v gii thch cho user khi c error. Nu user lm li nhiu
Textboxes th c th s c nhiu thng ip hin th ln lt ci ny tip
theo ci kia, mi thng ip lin h n mt Textbox c error. Cch y
Cc bi tp Microsoft .NET 146
cng tm c, nhng c th khin cho user bc mnh.
Control ErrorProvider cung cp mt cch n gin v thn thin cho
user bit Textbox no c d kin bt hp l. Control ErrorProvider cho
cc controls trn cng form mt property mi gi l Error on
ErrorProvider1 ( gi d l control ErrorProvider mang tn
ErrorProvider1).
Trong lc chng trnh chy, nu kim thy mt Textbox c li ta assign
mt TextString vo property Error on ErrorProvider1 ca Textbox y.
Lc by gi mt icon hnh du chm than trng s hin th bn phi
Textbox c Error. Nu user mouse cursor ln trn icon y th chng
trnh s hin th mt Tooltip vi tr s TextString ca property Error on
ErrorProvider1 ging nh trong hnh di y:
Cng vic assign mt TextString vo property Error on ErrorProvider1
ca mt Textbox c th c coded nh sau:
Private Sub BtnOK_Click( ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
BtnOK.Click
' Set error if TextBox txtName is blank
If txtName.Text = "" Then
' Assign error ToolTip message to Textbox txtName
ErrorProvider1.SetError(txtName, "You must supply a name!")
End If
End Sub
Cc bi tp Microsoft .NET 147
Trn y ta dng Event Click ca button BtnOK kim tra d kin
trong mi Textbox. C mt Event ca cc controls m ta cng c th
dng trong cng tc kim tra d kin ca mt TextBox. l Event
Validating. gy ra Event Validating ta cn phi dng property
CauseValidation ca cc controls. Thng thng, property
CauseValidation ca cc controls c set thnh True. TextBox txtName
ch to ra Event Validating khi chnh property CauseValidation ca n l
True v khi focus c di chuyn n mt control khc c property
CauseValidation l True.
Xin lu l khng nht thit Event Validating c to ra khi txtName
mt focus. Khi txtName mt focus th Textbox txtAge c focus (gi d
txtAge c tr s TabOrder ngay sau txtName) , nhng nu property
CauseValidation ca txtAge khng phi l True th phi i n khi focus
p ln mt control c property CauseValidation l True txtName mi
gy ra Event Validating.
Ta c th code cho Sub txtName_Validating nh sau:
Private Sub txtName_Validating( ByVal sender As Object, ByVal e As
System.ComponentModel.CancelEventArgs) _
Handles txtName.Validating
' Set error if TextBox txtName is blank
If txtName.Text = "" Then
' Assign error ToolTip message to Textbox txtName
ErrorProvider1.SetError(txtName, "You must supply a name!")
Else
' Clear the error ToolTip message for Textbox txtName and make error Icon invisible
ErrorProvider1.SetError(txtName, "")
End If
End Sub
Ci icon hnh du chm than trng l default icon ca ErrorProvider.
Mun dng mt icon khc ta ch cn assign icon y vo property Icon
ca ErrorProvider.
Menus
Cc bi tp Microsoft .NET 148
Mc du Menu Editor ca VB6 cung cp y cc phng tin lm
Menu v tng i d dng, VB.NET cho ta mt giao din cng thn
thin v t nhin hn thit k Menu.
Menu c thm vo form di dng mt control. Tuy Menu control nm
trong mt mm components pha di, nhng trong lc thit k, Menu
hin ra trong form y nh lc Runtime v bn ch cn in vo cc
menuitems cn thit. C hai loi menus: Main Menu (Menu dng thng
thng) v Context Menu (dng cho Pop-Up).
Menus
Main Menu l Menu cn bn m bn thy n dnh vo cnh trn ca mt
form. d gii thch, ta s dng mt th d to ra mt Editor tht n
gin bng VB.NET. Bn hy khi ng mt Windows Application mi
v thm mt Textbox vo trong form chnh. Set property MultiLine ca
Textbox thnh True n c th hin th nhiu hng, ng thi Stretch
(ko dn ra) ci Textbox cho ln ra lm ni ta c th nh vo mt bi
text.
K , thm mt Main Menu vo form. Ci menu Designer s kch ng
v bn ch cn nh vo chi tit cc menuItems v dng ca s Properties
set cc parameters.
Khi no bn select control Main Menu trong mm components l bn c
th edit cc MenuItems. Mun lm vic vi MenuItem no th select
MenuItem . Nhng ch c ch Type Here l ngh cho bn nh
thm vo mt MenuItem (Type Here nm pha di) , mt
MenuCommand mi (Type Here nm bn phi mt MenuCommand) hay
mt MenuSubItem (Type Here nm bn phi mt MenuItem).
Cc bi tp Microsoft .NET 149
Mun insert mt ln ngang gia MenuItem Paste v MenuItem Clear
All, bn select MenuItem Clear All ri right click v chn Insert
Separator trong Pop-Up Menu.
Mun ch nh Shortcut cho mt MenuItem, bn select MenuItem y ri
vo ca s Properties chn tr s cho property Shortcut. Tng t
nh vy cho property Checked lm mt checkmark hin ra bn tri
(pha trc) Text ca MenuItem.
Cc bi tp Microsoft .NET 150
Thm vo cc dng code sau y cho chng trnh. Khi doubleClick ln
MenuItem copyMenuItem ca s m ngun s m ra cho bn nh code
cho Private Sub copyMenuItem_Click:
Private Sub copyMenuItem_Click( ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles copyMenuItem.Click
' Copy the selected text to the Clipboard
Textbox1.Copy()
End Sub
Private Sub pasteMenuItem_Click( ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles pasteMenuItem.Click
'Paste the Clipboard text into Textbox1
Textbox1.Paste()
End Sub
Private Sub clearAllMenuItem_Click( ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles clearAllMenuItem.Click
' Clear everything in Textbox1
Textbox1.Text = ""
End Sub
Cc bi tp Microsoft .NET 151
Private Sub closeMenuItem_Click( ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles closeMenuItem.Click
' Close the form
Me.Close()
End Sub
Khi chy chng trnh, hnh di y s hin th:
Context Menus
Ta dng Context Menu Pop-Up mt Menu xng hp vi tnh hung
ng thi ca program khi user right click mt control trn form. Trong
VB6, Context Menu cng l mt MenuCommand thng thng nhng ta
thit k cho n invisible, ch khi no ta mun Pop-Up n th n mi
hin th.
Trong VB.NET, Context Menu l mt control ring, nhng ta edit n
cng ging nh Main Menu. Khi thm mt control ContextMenu vo
form ri, mi ln ta select n trong mm components th Context Menu
hin ra cnh trn ca form ging nh Main Menu. Lc Runtime, khi
Cc bi tp Microsoft .NET 152
user right click mt control c Context Menu th ContextMenu s hin th
v tr .
Bn hy doubleClick control ContextMenu trong hp ngh thm
mt Context Menu vo trong form. K set up cc MenuItem nh sau:
hin th ci Radio button bn tri mt MenuItem, bn phi lm hai
chuyn:
1. Set property Checked ca MenuItem thnh True
hin th mt checkmark hay mt hnh trn nh
(Radio button).
2. Set property RadioCheck ca MenuItem thnh True
khi no n hin th th c dng Radio button, thay
v mt checkmark.
Nh l ta dng checkmark khi mun cho user chn nhiu th cng mt
lc, v dng Radio button khi mun cho user ch chn mt nhim m
thi, tc l mutually exclusive. Tuy nhin, khc vi khi edit mt nhm
Radio buttons trong mt container trn form, VB.NET khng cn tr ta
cho hai Radio buttons trong mt menu cng hin ra. Do , bn phi t
qun l vn mutually exclusive trong code ca mnh.
ch nh ContextMenu1 Pop-up khi user right click Textbox1, bn ch
cn set property ContextMenu ca Textbox1 thnh ContextMenu1 (chn
Cc bi tp Microsoft .NET 153
n trong ci dropdown list ca comboxbox ca property ContextMenu
trong ca s Properties).
Khi bn chy chng trnh v right click Textbox1, ContextMenu1 s
hin th nh di y:
M ngun nm pha sau cc click events ca hai MenuItems ca
ContextMenu1 c lit k di y:
Private Sub blackOnWhiteMenuItem_Click( ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles blackOnWhiteMenuItem.Click
' Change colors of Textbox1
Textbox1.ForeColor = Color.Black
Textbox1.BackColor = Color.White
'Toggle the radio check
blackOnWhiteMenuItem.Checked = True
WhiteOnBlueMenuItem.Checked = False
End Sub
Private Sub WhiteOnBlueMenuItem_Click( ByVal sender As System.Object, _
Cc bi tp Microsoft .NET 154
ByVal e As System.EventArgs) Handles WhiteOnBlueMenuItem.Click
' Change colors of Textbox1
Textbox1.ForeColor = Color.White
Textbox1.BackColor = Color.Blue
'Toggle the radio check
blackOnWhiteMenuItem.Checked = False
WhiteOnBlueMenuItem.Checked = True
End Sub
property Checked ca hai MenuItems c coded h ci ny
True th ci kia phi False, tc l mutually exclusive. V MenuItem no
c tr s Checked l True th Radio button hin th pha trc n.
Sa i Menus lc Runtime
Ta c th sa i Menu lc Runtime, chng hn nh Context Menu
thng c nhng dng khc nhau ty theo trng thi ca mt control hay
form.
Mt th d khc l hin th danh sch cc files m chng trnh truy cp
trong qu kh. Thng thng ta cha tn cc files y trong Registry v
khi cn s c v load vo Menu.
Di y l code ch cch cho thm mt MenuItem vo trong mt
ContextMenu, v cch clear (xa) mi MenuItems. Ta bit rng
ContextMenu c mt property l collection ca nhng MenuItems. Do
mun thm mt MenuItem th cn tri qua ba bc:
1. Instantiate mt MenuItem.
2. ng k Event Handler ( y l AddressOf Sub
NewMenuItem_Click), m chng trnh s dng
x l Event Click ca MenuItem y.
3. Thm MenuItem y vo collection MenuItems ca
control ContextMenu.
Thm vo form hai buttons t tn l BtnAddMenuItem v
BtnClearContextMenu.
Cc bi tp Microsoft .NET 155
Private Sub BtnAddMenuItem_Click( ByVal sender As System.Object, ByVal e As System.EventArgs)
_
Handles BtnAddMenuItem.Click
'Add a menu item at the top of ContextMenu1
Dim AnewMenuItem As MenuItem ' Declare a MenuItem variable
' Create the new menu Item
AnewMenuItem = New MenuItem("New Menu Item!")
' Register EventHandler for Event Click of this new Menu item
AddHandler AnewMenuItem.Click, AddressOf Me.NewMenuItem_Click
' Add it to the collection MenuItems
ContextMenu1.MenuItems.Add(0, AnewMenuItem)
End Sub
Private Sub NewMenuItem_Click( ByVal sender As System.Object, ByVal e As System.EventArgs)
MessageBox.Show("You clicked new Menu Item!")
End Sub
Private Sub BtnClearContextMenu_Click( ByVal sender As System.Object, ByVal e As
System.EventArgs) _
Handles BtnClearContextMenu.Click
' Remove all the menu items from ContextMenu1
ContextMenu1.MenuItems.Clear()
End Sub
Sau khi bn click nt Add MenuItem, lc bn right click Textbox1, Pop-
up Menu s c thm mt MenuItem nh sau:
Cc bi tp Microsoft .NET 156
Th click new Menu Item trong ContextMenu1, chng trnh s hin th
thng ip You clicked new Menu Item!. By gi click nt Clear
ContextMenu ri right click Textbox1. ContextMenu1 b cleared nn
s khng hin th.
Duplicating Menus
Mt vic khc ta c th lm trong lc Runtime ca chng trnh l
cloning (to object song sinh). Th d, ta mun dng Edit menu ca
MainMenu1 lm ContextMenu (ging ging nh trong VB6) cho
Textbox1.
thc hin vic ny, ta dng method CloneMenu(). Di y l code
ta dng thay th ContextMenu1 trong chng trnh bng Edit menu
ca MainMenu1.
Private Sub BtnCloneMenu_Click( ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles BtnCloneMenu.Click
' Instantiate a new ContextMenu object
Dim newContextMenu As New ContextMenu()
' Add a clone copy of EditMenu to this new ContextMenu's collection of MenuItems
newContextMenu.MenuItems.Add(editMenuItem.CloneMenu)
Cc bi tp Microsoft .NET 157
' Assign this new Context Menu to Textbox1
Textbox1.ContextMenu = newContextMenu
End Sub
Khi ng chng trnh, click nt Clone Menu, ri right click TextBox1,
ContextMenu mi s hin th nh di y:
Lu : V CloneMenu() clone hon ton Object editMenuItem, k c cc
Event Handlers ca cc SubMenuItems nn ta khng cn phi lm thm
g c.
Mun tr li trng thi c, tc l dng ContextMenu1 cho Textbox1, ta
ch cn reassign ContextMenu1 vo property ContextMenu ca Textbox1
nh sau:
Textbox1.ContextMenu = ContextMenu1
MDI Forms
Trong VB6 ta to mt MDI (Multiple Document Interface) form bng
cch set property MDIChild ca form y thnh True. Mt form nh th
ch c th c dng lm child form, tc l n cn mt form MDI parent
hin th trong y. Ngoi ra, mi application ch c th c mt form
Cc bi tp Microsoft .NET 158
MDI parent duy nht v ch trong lc thit k ta mi c th ch nh c
tnh ca mt form l MDIChild. Mt form khng th tr thnh mt
MDIChild lc Runtime.
Trong VB.NET, mt form c th tr thnh mt MDI child lc Runtime
bng cch set property MDIParent ca form y nhm vo mt form
MDI parent. Do , mt form c th va l MDIchild form, va l form
bnh thng ty theo hon cnh. Tht ra, ngc vi VB6, ta khng th set
property MDIParent lc thit k, m phi lm lc Runtime.
Ging nh VB6, trong VB.NET ta c th hin th nhiu forms MDIChild
trong mt form MDI parent, khi parent form di chuyn th mang theo cc
forms con. Khi hin th nhiu child forms, ta c th dng property
ActiveForm bit child form no hin thi l Active.
Ta th khi ng mt Windows Application mi. i tn Form1 thnh
ParentForm v ch nh n lm MDI parent bng cch set property
IsMDIContainer ca n thnh True. K thm mt form v i tn n
thnh ChildForm. Di y l code thm hai child forms vo
ParentForm v hin th chng:
' Declare child forms of type ChildForm
Private WithEvents FirstChild As ChildForm
Private WithEvents SecondChild As ChildForm
Private Sub ParentForm_Load( ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles MyBase.Load
' Instantiate an Object of type Childform
FirstChild = New ChildForm()
' Make this form the MDI Parent of FirstChild
FirstChild.MdiParent = Me
FirstChild.Text = "First Child Form" ' Set Title
' Show FirstChild
FirstChild.Show()
Cc bi tp Microsoft .NET 159
' Instantiate the second Object of type Childform
SecondChild = New ChildForm()
' Make this form the MDI Parent of SecondChild
SecondChild.MdiParent = Me
SecondChild.Text = "Second Child Form" ' Set Title
' Show SecondChild
SecondChild.Show()
End Sub
cung cp mt Menu hin th danh sch cc forms MDIchild ca
ParentForm, ta thm control MainMenu vo ParentForm. K , to mt
MenuItem tn Windows v set property MDIList ca n thnh True.
Property ny s khin danh sch cc forms child t ng hin th lm
nhng menu items nm pha di Menu Windows. Danh sch ny t
ng cp nht khi mt child form tr thnh Active, c thm vo, hay b
ly ra.
Parent MDI form c mt method tn l LayoutMDI t ng sp t v
tr cc forms child theo kiu Cascade hay Tile layout. Thm mt
MenuItem tn Tile Vertical v nht my hng code di y vo form
x l Event click ca n:
Private Sub tileVerticalMenuItem_Click( ByVal sender As System.Object, ByVal e As
System.EventArgs) _
Handles tileVerticalMenuItem.Click
Me.LayoutMdi(System.Windows.Forms.MdiLayout.TileVertical)
End Sub
Khi ng chng trnh, by default hai forms childs c layout kiu
Cascade. Trong Menu Windows c hin th title ca hai forms child v
cho bit Second Child Form l Active form.
Cc bi tp Microsoft .NET 160
Nu bn click Tile vertical, hai forms child s c layout kiu Tile nh
di y:
Cc bi tp Microsoft .NET 161
Bi 12
Nhng chc nng mi trong giao din ca s ca
VB.NET (phn V)
Toolbars
Toolbars trong .NET c nng cp bng cch thm chc nng cho
cc ToolBarButtons trong collection ca nhng buttons y.
dng th Toolbar control, bn hy khi ng mt Project mi v t
mt Toolbar vo form chnh bng cch doubleclick ln Toolbar icon
trong Toolbox. Mt Toolbar s hin ra nm ngay di tiu ca form.
K rightclick ln Toolbar y v chn Properties edit property
Buttons Collection bng cch click ln ch (Collection) ri click ba du
chm pha bn phi hin th ToolbarButton Collection Editor.
Bn hy Add vo Toolbar ba buttons vi nhng c tnh sau:
i property Text ca button th nht
(ToolbarButton1) ra Close v ta mun ng chng
trnh khi user click ln button y. By default Style ca
ToolbarButton l PushButton.
i property Style ca button th nh
(ToolbarButton2) ra Separator v ta mun dng n
to khong cch gia button th nht v button th
ba.
i property Text ca button th ba
(ToolbarButton3) ra Background Colour v
property Style ra DropDownButton v ta mun dng
n nh mt Combobox.
Khi chy th chng trnh ta s thy hnh ging nh di y:
Cc bi tp Microsoft .NET 162
By gi ta s vit code x l Event Click ca Toolbar. Ch c mt
handler, Sub ToolBar1_ButtonClick, c dng cho tt c cc buttons.
Ta phn bit Button no da vo Index ca n, ging ging nh mt
array of buttons trong VB6. Nu user click button th nht ta s c
ToolBar1.Buttons.IndexOf(e.Button) bng 0, lc y ta s Close form
chnh.
Private Sub ToolBar1_ButtonClick( ByVal sender As System.Object, ByVal e As
System.Windows.Forms.ToolBarButtonClickEventArgs) Handles ToolBar1.ButtonClick
Select Case ToolBar1.Buttons.IndexOf(e.Button)
Case 0 ' Close Button
Me.Close()
Case 1 ' Never happens because the Button is a Separator
Case 2 '
MessageBox.Show("You clicked the third button")
End Select
End Sub
Nu khng mun dng ToolBar1.Buttons.IndexOf(e.Button), bn cng c
th so snh Buttons vi operator Is nh sau:
If e.Button Is ToolBarButton1 Then
Me.Close()
ElseIf e.Button Is ToolBarButton3 Then
Cc bi tp Microsoft .NET 163
MessageBox.Show("You clicked the third button")
End If
K chng ta cho t mt ContextMenu tn ContextMenu1 vo form
v assign n vo property DropDownMenu ca button th ba nh trong
hnh di y:
Nu khng mun assign ContextMenu1 vo button th ba trong lc thit
k, bn c th thc hin vic y bng code lc form mi load nh sau:
Private Sub frmToolbar_Load( ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles MyBase.Load
ToolBarButton3.DropDownMenu = ContextMenu1
End Sub
Bn hy edit hai menuItems cho ContextMenu1: mt ci tn mnuXm
vi Text l Xm v ci kia tn mnuTrng vi Text l Trng.
Khi chy chng trnh, nu bn click ci thanh c du tam gic en nm
bn phi button th ba, ContextMenu1 s hin ra bn dng. Nu bn
click button th ba, chng trnh cng generate mt Click Event nhng
hin gi ta khng dng n, ch hin th mt s ip nh xc nh l c
Event Click y.
Nh th, ta thy .NET ghp mt ContextMenu vo mt ToolbarButton
bin n thnh mt DropDownMenu. C iu sau khi user chn mt
Item trong ContextMenu/DropDownMenu, Text ca Item khng c
hin th ging nh trong mt ComboBox. Nu bn kh tnh v mun c
chuyn th phi t lm ly nh cho thy trong code di y:
Private Sub frmToolbar_Load( ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles MyBase.Load
ToolBarButton3.DropDownMenu = ContextMenu1
ToolBarButton3.Text = "Xm"
End Sub
Private Sub mnuXm_Click( ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
mnuXm.Click
MessageBox.Show("Bn chn mu Xm")
Cc bi tp Microsoft .NET 164
ToolBarButton3.Text = "Xm"
End Sub
Private Sub mnuTrng_Click( ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles mnuTrng.Click
MessageBox.Show("Bn chn mu Trng")
ToolBarButton3.Text = "Trng"
End Sub
Khi chy chng trnh bn s thy nh sau:
ListBox
Items l mt collection of Strings
Mi dng n, ta s thy .NET ListBox rt ging ListBox trong VB6.
Tin ch by gi ta c th edit cc string Items ca ListBox trong mt
editor nho nh s hin ra khi ta click vo ch (Collection) ca property
Items:
Cc bi tp Microsoft .NET 165
Cc Items c cha trong mt collection tn Items, do ta c th lm
vic vi mi chc nng ca mt collection nh Add, Clear, Insert,
Remove, RemoveAt, Count .v.v..
Th d nh ta cho thm bn Items vo Listbox1 lc Form_Load nh sau:
Private Sub frmListbox_Load( ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles MyBase.Load
' Add individual items
ListBox1.Items.Add("Kng-gu-ru")
ListBox1.Items.Add("Cng")
' Add more than one items by instantiating an object with items list enclosed in curly brackets {}
ListBox1.Items.AddRange(New Object() {" iu", "Gu Panda"})
End Sub
Nu trong khi chy chng trnh, bn thm nhiu Items vo ListBox v
mun trnh update display Listbox nhiu ln, bn c th kp code gia
hai statements BeginUpdate v EndUpdate nh sau:
' Shutdown the painting of the ListBox as items are added.
Cc bi tp Microsoft .NET 166
ListBox1.BeginUpdate()
' Loop through and add 50 items to the ListBox.
Dim x As Integer
For x = 1 To 50
ListBox1.Items.Add("Item " & x.ToString())
Next x
' Allow the ListBox to repaint and display the new items.
ListBox1.EndUpdate()
Ging nh trong VB6, property MultiColumn hin th Items trong
nhiu ct nu c set thnh True, property SelectionMode nu bng
MultiExtended th cho ta select nhiu Items cng mt lc.
Tuy nhin, cc Items c chn s c mt trong mt collection ch
khng phi c Selected(i)=True nh trong VB6.
Mun select mt Item lc run-time ta dng code nh sau:
' Select three items (2nd, fourth and sixth) from the ListBox.
ListBox1.SetSelected(1, True) ' 1 is index of 2nd item
ListBox1.SetSelected(3, True)
ListBox1.SetSelected(5, True)
Trong th d ti y ta c ListBox1 vi danh sch cc con vt trong S
Th Saigon. Button List Items s lit k danh sch ny. cch ta hin
th mt Item vi expression Listbox1.Items(i).ToString.
Private Sub BtnListItems_Click( ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles BtnListItems.Click
Dim i As Integer
Dim Mess As String
' make up the list of Items separated by CarriageReturn/LineFeed
For i = 0 To ListBox1.Items.Count - 1
Mess &= (ListBox1.Items(i).ToString) & vbCrLf
Next
' Show the list
Cc bi tp Microsoft .NET 167
MessageBox.Show(Mess)
End Sub
Sau khi set property SelectionMode ca Listbox1 ra MultiExtended,
code di y s lit k danh sch cc items c chn vi index ca
chng:
Private Sub BtnListSelectedItems_Click( ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles BtnListSelectedItems.Click
Dim i As Integer
Dim Mess As String
' make up the list of Selected Items separated by CarriageReturn/LineFeed
' Collection SelectedIndices contains the index of selecteditems
For i = 0 To ListBox1.SelectedItems.Count - 1
Mess &= (ListBox1.SelectedIndices(i).ToString) & ":" & (ListBox1.SelectedItems(i).ToString) &
vbCrLf
Next
' Show the list
MessageBox.Show(Mess, "Selected Items", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub
Cc bi tp Microsoft .NET 168
Items l mt Array of Objects
ListBox ca .NET khng h tr ItemData nh trong VB6. ItemData l
mt array cha cc con s tng ng vi nhng Items trong List array
ca ListBox trong VB6. Tc l mi ListBox Item trong Vb6 c th c
ch nh trc mt con s i din n. Khi user select List(i), ta c th ly
ra ItemData(i) ca List Item y.
Tht ra Items ca .NET Listbox cng c th l mt Array of Objects,
khng nht thit phi l mt collection of Strings nh ta dng.
Di y l code ta nh ngha mt Class tn LBItem, on dng code
th Add mt Array of Objects loi LBItem vo Listbox1:
Public Class LBItem
Private mList As String
Private mItemData As Integer
' List Item of Listbox
Public Property List() As String
Get
Return mList
End Get
Set ( ByVal Value As String)
Cc bi tp Microsoft .NET 169
mList = Value
End Set
End Property
' ItemData of Listbox
Public Property ItemData() As Integer
Get
Return mItemData
End Get
Set ( ByVal Value As Integer)
mItemData = Value
End Set
End Property
' Function to return a string representing this item for display
Overrides Function ToString() As String
Return mList
End Function
End Class
Sau khi Add mt Array of Objects vo ListBox1 ta phi ch nh lm th
no hin th mt Item. Th d nh dng property List ca LBItem nh
di y:
' Indicate that Property List of LBItem will be used to display
ListBox1.DisplayMember = "List"
Nu ta khng ch nh DisplayMember, tc l ListBox1.DisplayMember
= "" th ListBox1 s dng Function ToString ca LBItem hin th.
Ngoi ra, tr v mt value ging nh ItemData ca List Item ta ch
nh ValueMember nh di y:
Private Sub BtnAddOjects_Click( ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles BtnAddOjects.Click
' Clear all items in Listbox1
ListBox1.Items.Clear()
Cc bi tp Microsoft .NET 170
Dim Objs(5) As LBItem
' Create an array of 6 Objects of LBItem
Dim i As Integer
For i = 0 To 5
Objs(i) = New LBItem()
Objs(i).List = "Line " & i.ToString
Objs(i).ItemData = i + 100
Next
' Add the array of objects to Listbox1
ListBox1.DataSource = Objs
' Indicate that Property List of LBItem will be used to display
ListBox1.DisplayMember = "List"
' Indicate that Property ItemData of LBItem will be used to return a value
ListBox1.ValueMember = "ItemData"
End Sub
Khi chy chng trnh ny, sau khi click nt Add Objects clear
ListBox1 v Add 6 Objects mi, nu bn click hng th 4 trong ListBox
s thy hnh di y:
Code x l Event SelectedIndexChanged (tc l Event Click trc y)
ca ListBox1 ging nh di y:
Cc bi tp Microsoft .NET 171
Private Sub ListBox1_SelectedIndexChanged( ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles ListBox1.SelectedIndexChanged
Try
If ListBox1.SelectedValue <> "" Then
MessageBox.Show(ListBox1.SelectedValue & " of " & ListBox1.SelectedItem.ToString,
"Selected value")
End If
Catch ex As Exception
' Do nothing, ignore this error
End Try
End Sub
Nh th ta implemented (thi hnh) cho .NET ListBox mt chc nng
tng ng vi ItemData ca ListBox trong VB6.
.NET ListBox khng h tr Style Checkbox, nhng ta c th dng
CheckedListBox.
ComboBox
V ComboBox tha k t ListBox nn tt c nhng g ta bit v ListBox
u p dng cho ComboBox. c bit by gi ComboBox c property
MaxDropDownItems cho ta quyt nh hin th bao nhiu items khi
danh sch c m ra.
Km theo y l mt chng trnh biu din ComboBox trong ta dng
Property ValueMember ca ComboBox tr v mt tr s i din
Item. Data trong ComboBox1 c loaded t mt Access2000 database
table bng code sau y:
Private Sub frmCombo_Load( ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles MyBase.Load
Dim ds As New DataSet () ' Instantiate a Dataset
' Instantiate an OleDbDataAdapter for Access2000 database Authors.mdb and return table Authors
Dim myData As New OleDbDataAdapter("Select * from Authors",
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=..\Authors.mdb")
myData.Fill(ds, "Authors") ' Load table Authors into Dataset
Cc bi tp Microsoft .NET 172
With ComboBox1
' Bind Table Authors to ComboBox1
.DataSource = ds.Tables("Authors")
' Make Property/Datafield FullName the DisplayMember of ComboBox1
.DisplayMember = "FullName"
' Make Property/Datafield AuthorID the ValueMember of ComboBox1
.ValueMember = "AuthorID"
End With
End Sub
Chng ta ch nh record datafield FullName lm DisplayMember ca
ComboBox1 v datafield AuthorID lm ValueMember ca ComboBox1.
Ta truy cp data ca c s d liu bng cch dng mt DataAdapter loi
OleDbDataAdapter khi cho n mt SQL CommandText: "Select *
from Authors" v mt connection string, trong c cho bit database
driver: Microsoft.Jet.OLEDB.4.0 v tn ca database ..\Authors.mdb.
File Authors.mdb nm chung vi m ngun ca chng trnh trong parent
folder ca folder bin, ni cha ComboBox.exe.
K ta dng DataAdapter b table Authors vo dataset ds. Cch lm
vic ny tng t nh ADO (Active Data Object) trong VB6. C im
khc l Dataset c th cha nhiu tables (recordsets) v n hot ng nh
mt cached disconnected database trong b nh. K thut ny c tn l
ADO.NET v ta s bn thm nhiu v n trong tng lai.
Mi ln user select mt item mi t ComboBox1, chng trnh s hin
th AuthorId, l ValueMember trong Label1.
Private Sub ComboBox1_SelectedIndexChanged( ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles ComboBox1.SelectedIndexChanged
Try
'Display the selected valueMember
Label1.Text = ComboBox1.SelectedValue
Catch
End Try
Cc bi tp Microsoft .NET 173
End Sub
y c hai cch ta select mt ComboBox item bng coding. Cch
th nht l cho bit AuthorId (ValueMember), user clicks button Select
by AuthorId thy kt qu:
Private Sub BtnSelectbyAuthorId_Click_1( ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles BtnSelectbyAuthorId.Click
'Use Try to ignore error if operation fails
Try
' Select the ComboBox Item whose valueMember equal txtAuthorId.Text
ComboBox1.SelectedValue = txtAuthorId.Text
Catch
End Try
End Sub
v cch th hai l cho bit FullName (DisplayMember), user clicks
button Select by Name thy kt qu:
Private Sub BtnSelectByName_Click( ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles BtnSelectByName.Click
'Use Try to ignore error if operation fails
Try
' Select the ComboBox Item whose DisplayMember equal txtFullName.Text
' FindString returns the index of the found item
ComboBox1.SelectedIndex = ComboBox1.FindString(txtFullName.Text)
Catch
End Try
End Sub
Khi chy chng trnh, bn s thy hnh nh CCdi y. Trong hnh
y, MaxDropDownItems ca ComboBox1 c set bng 4.
Cc bi tp Microsoft .NET 174

You might also like