Tải bản đầy đủ (.pdf) (50 trang)

Tài liệu Programming Microsoft SQL Server 2000 with Microsoft Visual Basic .Net - P6 ppt

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (890.56 KB, 50 trang )

End Sub

Going from a hexadecim al value t o a Long value is m ore com plicated for a couple
of reasons. First , t here is no built - in funct ion. Second, hexadecim al num bers need
to be converted on a charact er- by-charact er basis t hat reflect s the ch ar act er’s
posit ion in t he hexadecim al num ber. Th is t ask is furt her com plicat ed by that fact
that charact ers go outside t he decim al range of 0 through 9 t o t he hexadecim al
range of 0 t hrough F. The following sam ple perfor m s a check t o verify that t he
hexadecim al st ring value doesn’t exceed t he m axim um Long value. The hex
representat ion for t he m axim um Long value is 7FFFFFFFFFFFFFFF.
Aft er perform ing a bound check for t he m ax im um hexadecim al value, t he
Convert Hex ToLng pr ocedure st art s a loop t hat it erat es t hrough successive
charact ers in t he hexadecim al num ber. St art ing at the far right charact er, t he
loop evaluates each ch aract er. The evaluat ion m ultiplies t he hex charact er’s
decim al value by a power of 16. The pow ers range in value from 0 for the far
right charact er t o up to 15 for t he sixt eent h hex charact er ( if t here is one) . When
the Convert HexToLng procedur e finish es looping t hrough the charact ers in the
hexadecim al num ber, t he pr ocedur e presents a m essage box wit h t he decim al
value of t he hexadecim al num ber in Text Box1.
Private Sub Button4_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button4.Click

’Call program to convert a hexadecimal number to
’a Long number.
ConvertHexToLng()
End Sub

Sub ConvertHexToLng()

’Assign TextBox1 contents to hexStr.
’Dim strValue As String = TextBox1.Text


Dim hexStr As String = TextBox1.Text

’If hexStr greater than 7FFFFFFFFFFFFFFF, then abort.
Dim hexchars As Integer = Len(hexStr)
If (hexchars = 16 And hexStr.Chars(0) > “7”) Or _
hexchars > 16 Then
MsgBox(“Hex values beyond 7FFFFFFFFFFFFFFF “ & _
“generate an exception. Enter a smaller “ & _
“hex value.”)
Exit Sub
End If

’Variable lnghexstr stores long of hex string in TextBox1,
’and i is a loop counter value.
Dim lnghexstr As Long
Dim i As Integer

’Loop through characters to compute decimal equivalent
’of hex string.
lnghexstr = 0
For i = 0 To hexchars - 1
Select Case Mid(UCase(hexStr), hexchars - i, 1)
Case “0"
lnghexstr += CLng(0 * (16 ^ i))
Case “1"
lnghexstr += CLng(1 * (16 ^ i))
Case “2"
lnghexstr += CLng(2 * (16 ^ i))
Case “3"
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

lnghexstr += CLng(3 * (16 ^ i))
Case “4"
lnghexstr += CLng(4 * (16 ^ i))
Case “5"
lnghexstr += CLng(5 * (16 ^ i))
Case “6"
lnghexstr += CLng(6 * (16 ^ i))
Case “7"
lnghexstr += CLng(7 * (16 ^ i))
Case “8"
lnghexstr += CLng(8 * (16 ^ i))
Case “9"
lnghexstr += CLng(9 * (16 ^ i))
Case “A"
lnghexstr += CLng(10 * (16 ^ i))
Case “B "
lnghexstr += CLng(11 * (16 ^ i))
Case “C"
lnghexstr += CLng(12 * (16 ^ i))
Case “D"
lnghexstr += CLng(13 * (16 ^ i))
Case “E"

lnghexstr += CLng(14 * (16 ^ i))
Case “F"
lnghexstr += CLng(15 * (16 ^ i))
End Select
Next i

’Display long value for hex string.

MsgBox(“Long value for text box equals:” & vbCrLf & _
lnghexstr.ToString)
End Sub


I nheriting Cla sses
Classes are great because t hey package blocks of Visual Basic code for easy
reuse. Class inherit ance m ult iplies t hat cor e benefit of classes by let ting one class
inherit t he propert ies, m et hods, and events of anot her class. I nherit ance for
cust om classes is new t o Visual Basic program m ers wit h Visual Basic .NET. This
sect ion begins wit h an overv iew of design issues and keywords for im plem ent ing
class inher it ance. Next I cover a couple of sam ples that dem onst rat e the synt ax
for im plem enting inher it ance w it h different keyw ords. At t he sect ion’s close, you
will discover a discussion of overloading. This feat ure can m ake one m ethod or
propert y wit hin a class easily accept m any different t ypes of value inputs. I nst ead
of building capabilit ies int o applications by layering one class on t op of anot her or
m anually coding a class to t est m ult iple value t ypes and then respond
appropriat ely t o t he input value t ype, t he Overloads keyw ord expands the
capabilit ies of a single class. I cover t he Overloads keyw ord in t his sect ion
because of it s resem blance t o the Over riding keyword— one of t he keyw ords for
m anaging inherit ance— and because Over loads widens t he capabilit ies of a class
m uch as inherit ance can.
Ov er vie w of I nher it a nce
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
I nherit ance is for classes. I t let s one class inherit t he propert ies, m ethods, and
events of anot her class. My discussion of inherit ance focuses on propert ies and
m et hods t o sim plify t he present at ion. ( See t he “Program m ing Events” sect ion
lat er in t his chapter for m or e on m anaging class event s.) When Class B inherit s
Class A, Class B can offer the sam e m et hods, propert ies, and event s of Class A.
I n addit ion, Class B can offer new propert ies and m et hods as well as m odified

versions of t he properties and m et hods in Class A. Visual Basic developers didn’t
have t his capability for cust om st and-alone classes wit h v ersions of Visual Basic
prior t o t he .NET v ersion. Therefore, it is nat ur al t hat y ou need t o learn som e new
concepts and sy nt ax t o take advantage of inherit ance. We can st art our new
inherit ance vocabulary by r eferr ing t o t he inherit ed class as t he base class. The
class t hat inher it s a base class is a derived class.
When one class inherit s fr om anot her class, the der ived class m ust cont ain a
declaration st at ing from which class it inherit s propert ies and m et hods. Visual
Basic .NET uses an I nherit s st atem ent t o m ake t he declarat ion. The I nherits
st at em ent takes as its argum ent t he nam e of t he base class. You can have j ust
one class nam e as the argum ent for I nherit s. Therefore, a class can inherit fr om
at m ost one ot her class at a tim e. I f t he der ived class adds any new m et hods, it
can offer t he m et hods of t he base class along wit h it s ow n new m et hods. I n
addit ion t o offer ing new m et hods, t he derived class can offer m odified
im plem entat ions of one or m ore m et hods from t he base class. Anot her new
inherit ance t erm in Visu al Basic .NET is polym orphism . I t describes t he abilit y of a
der iv ed class t o change t he im plem entat ion of a base class m em ber, su ch as a
propert y or a m et hod. An applicat ion can inst ant iat e inst ances for a derived class
and it s base class. I n t his way, t he applicat ion can invoke an unm odified m et hod
from a base class and an updat ed m et hod wit h t he sam e nam e from a deriv ed
class.
I n order for Visual Basic .NET t o m odify a base class m ethod in a der ived class,
your class m et hods require special keyw ords. Fir st , t he base class m ust m ark t he
m et hod nam e w it h the Overridable keyword, such as in the following code:
Class MyBaseClass
Overridable Function One () As Double
’Code for returning a value.
End Function
End Class


I n addit ion t o a keywor d in t he base class, you need a cor responding keyword,
Overrides, in the der ived class. This k eyword m ust be applied t o a m et hod in t he
der iv ed class wit h t he sam e nam e as t he one in t he base class whose
im plem entat ion y ou want t o ch ange. For exam ple
Class MyDerivedClass
Inherits MyBaseClass
Overrides Function One () As Double
’New code for returning a value.
End Function
End Class

As you can see, im plem ent ing polym orphism requir es planning. That is, you m ust
m ark t he base class t hat you want over ridden in derived classes w it h t he
Overridable key word. You m ust also sy nchr onize m ethod nam es bet ween t he
base and derived classes. The m et hod nam es wit hin a class— eit her base or
der iv ed— should generally be dist inct . I n general, you should also keep t he
m et hod and propert y nam es dist inct bet ween base and derived classes. Using t he
sam e nam e for a m et hod or a propert y in bot h base and derived classes has a
special m eaning that we will consider short ly.
I n order for a der ived class to refer back to a m et hod or propert y in a base class,
you need t o use t he special MyBase keyw ord. You will typically use t he My Base
keyw ord wit hin a funct ion in a der ived class t hat ov errides an ident ically nam ed
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
funct ion in a base class. You can also use t he MyBase keyw ord t o set and get
propert y values for a base class from a derived class. Then you can use the
MyBase k eyword to invoke a m et hod w it h t he values that you passed t o the base
class. For exam ple, MyBase.One() in a derived class invokes t he One m et hod in
the base class.
The Shadows keyword can apply to propert ies and m et hods in a derived class.
This keyw ord essent ially block s the availabilit y of identically nam ed propert ies

and m et hods in a base class. I n a sense, t he Shadows keyword for a propert y or
m et hod in a derived class cast s a shadow over an ident ically nam ed property or
m et hod in a base class. The Shadows keyw ord is m ore flexible and pow erful t han
the Ov erridable/ Ov err ides keyw ords. For exam ple, t he Ov er ridable/ Overrides
keyw ords apply only t o m et hods im plem ented wit h sub procedures or funct ion
procedures. The Shadow s keyword apples t o m et hods as well as propert ies. I n
addit ion, you can shadow a m et hod in a base class w it h a property in a derived
class. The Shadows k eyword rem oves t he dependence of a derived class on an
ident ically nam ed obj ect in a base class. Th is insu lat es t he derived class from any
changes t o t he base class t hat could inadvert ent ly cause an er ror in t he derived
class. The Overridable/ Ov errides k eywords don’t offer t his prot ect ion for a der ived
class from ch anges m ade in a base class.
The Overloads keyw ord isn’t st rictly an inher it ance topic, but t his keyword
pert ains t o classes, and it s nam e is sim ilar to Ov err ides. I n addit ion, using t he
Overloads keyword on a funct ion procedure, sub procedure, or propert y
procedure can alt er t he behavior of t he procedure. How ever, t he Overloads
keyw ord can apply t o m et hods or pr opert ies w it hin t he sam e class. A com m on
use of t he Overloads k eyword is t o enable m ult iple versions of a funct ion
procedure t o operat e as one. Each funct ion procedure in a set of overloaded
funct ion procedures has the sam e nam e. However, t he argum ent types change
for each funct ion procedure wit hin a set . Therefor e, one version of a m et hod can
accept a st ring argum ent , but anot her version can accept a double dat a type as
an ar-gum ent. The .NET Fram ework w ill aut om at ically invoke t he right funct ion
procedure based on an input ’s dat a type! That ’s t he power of t he Overloads
keyw ord.
An I nheriting a nd Over riding Sa m ple
Any Windows applicat ion applying class inherit ance will cont ain at least t hree
units of code. You need t wo unit s of code for t he classes: one for t he base class
and a second for t he derived class. A t hird unit of code is necessary t o inst antiat e
one or m ore classes and invoke t he m et hods or m anipulat e t he pr ocedures in the

der iv ed class or it s base class. I n a Windows application, y ou can inst antiat e
classes and m anipulat e the inst ances from event procedures for but t ons on a
form . One or m ore text boxes on a form can provide vehicles for users to specify
input values as argum ents for m et hods and propert ies.
The sam ple for t his sect ion is a Windows application t hat includes a form ( For m 1)
wit h m ult iple butt ons and text boxes for users t o m anipulat e. The first sam ple
uses But t on1 along wit h Text Box1 and Text Box2. Click ing But t on1 launch es an
event procedure that instantiat es a base class, Arit hm et icClass1 , and a derived
class, Class1. The procedur e m anipulat es these class inst ances in various way s
wit h input from t he ent ries in Text Box1 and Text Box2. I will det ail t he
m anipulat ions by describing t he But t on1_Click event pr ocedure aft er discussing
the code in t he Arit hm et icClass1 and Class1 classes.
N ot e
The sam ple for t his sect ion and the next two sect ions
dem onst rat ing inherit ance with Visual Basic .NET all use t he
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
sam e solut ion, I nherit ingSam ple. You can double- click
I nherit ingSam ple.sln in Windows Explorer to open t he
solution in Visual St udio. To run t he applicat ion from
Windows Explorer, invoke the I nheritingSam ple1.exe file.
The filenam e for t he .ex e file ret ains the original nam e for
the solut ion.
Arit hm eticClass1 is a variat ion of t he st and- alone class in t he Arit hm et icClass
proj ect discussed in t he “Cr eating and Using Class Refer ences” sect ion. This base
class resides in t he I nherit ingSam ple solut ion. The code for t he base class follows.
I t begins by specifying t wo writ e-only propert ies.
Arit hm eticClass1 also sp ecifies two m et hods— bot h based on funct ion procedures.
The Add2dbls m ethod follows direct ly from t he Arit hm et icClass present ed earlier
in this chapt er; t he m et hod adds t wo values wit h a Double value t ype. A sub
procedure im plem ent s this m et hod. The input for t he funct ion procedure is fr om

the Writ eOnly propert ies, which sp ecify the double values t o add. A funct ion
procedure im plem ent s the second m et hod, Add2dbls2, in Arit hm et icClass1. Using
argum ents for the funct ion procedure elim inat es t he need to rely on propert ies t o
specify t he values t o add. The Ov err idable k eyword appears at t he st art of the
Add2dbls2 m et hod specificat ion. This m eans t hat anot her class inherit ing
Arit hm eticClass1 can ov err ide t he code for t he m et hod t hat appears below .
Public Class ArithmeticClass1
Private dbl1 As Double
Private dbl2 As Double

’WriteOnly property named dblFirst.
Public WriteOnly Property dblFirst() As Double
Set(ByVal dblValue As Double)
dbl1 = dblValue
End Set
End Property

’WriteOnly property named dblSecond.
Public WriteOnly Property dblSecond() As Double
Set(ByVal dblValue As Double)
dbl2 = dblValue
End Set
End Property

’Add dbls.
Function Add2dbls() As Double
Return (dbl1 + dbl2)
End Function

’Overridable version of Add dbls.

Overridable Function Add2dbls2(ByVal MyNum1 As Double, _
ByVal MyNum2 As Double) As Double
Add2dbls2 = MyNum1 + MyNum2
End Function

End Class

The code for Class1 has three m aj or sect ions; t he full list ing for t he class appears
next . The first sect ion inherit s Ar it hm et icClass1. The I nherit s st at em ent m akes
Class1 a der ived class wit h Arit hm et icClass1 as it s base class. Class1 can
reference all t he propert ies and m et hods of Arit hm et icClass1 t hrough t he MyBase
keyw ord.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
The next sect ion in Class1 adds a new m et hod wit h t he Nt hPower funct ion. The
funct ion com put es t he value of t he base value t o a power, such as 2
3
equaling 8.
This funct ion accepts argum ent s for t he base and power variable values.
The final sect ion of code in Class1 defines a new im plem ent at ion for t he
Add2dbls2 m et hod init ially specified in t he base class. (See t he preceding code for
Arit hm eticClass1.) The Overrides k eyword at t he beginning of the m et hod
specificat ion in Class1 along w it h t he m at ching Overridable keyword for t he sam e
m et hod nam e in Arit hm et icClass1 perm it s t he override. The new im plem ent at ion
for t he Add2dbls2 m et hod doubles t he value com put ed in t he base class. The
MyBase k eyword facilit at es t he refer ence back t o t he base class. The argum ent s
passed to t he Add2dbls2 m et hod in Class1 transfer t o t he base class through t he
argum ents in t he expression containing t he My Base k eyword.
Public Class Class1
’Class1 class inherits from ArithmeticClass1.
Inherits ArithmeticClass1


’Added method to complement inherited method
’from ArithmeticClass1.
Public Function NthPower(ByVal base As Double, _
ByVal power As Double) As Double
NthPower = (base ^ power)
End Function

’The Add2dbls2 method in Class1 overrides the
’overridable Add2dbls2 method in ArithmeticClass1.
Overrides Function Add2dbls2(ByVal MyNum1 As Double, _
ByVal MyNum2 As Double) As Double
’The following code calls the original method in the base
’class, and then modifies the returned value.
Add2dbls2 = MyBase.Add2dbls2(MyNum1, MyNum2) * 2
End Function

End Class

The Click event for Bu tt on1, which appears nex t, begins by hiding som e cont rols
that aren’t necessary for t his use of t he form . Then t he event procedure
inst ant iat es Arit hm et icClass1 as t he arclass1 variable and Class1 as the c1
variable. The procedure uses t wo t ext boxes on t he form so t hat users can specify
double values for the m ethods in t he classes. Because t he text box values require
conversion t o m ake t hem Double values for t he procedures im plem ent ing t he
m et hods, t he sam ple com put es t he conversion once and st ores t he result s in t wo
variables w it h a Double value specificat ion.
Aft er concluding t he pr eceding pr elim inary st eps, t he event procedure st art s
com put ing and displaying result s. I nit ially t he procedure passes the Double
values saved in num 1 and num 2 t o the propert y procedures assigning values to

the dblFirst and dblSecond propert ies in Arit hm et icClass1. Next t he procedure
inv okes t he Add2dbls m et hod w it hin t he Arit hm et icClass1 and co- nvert s the
outcom e t o a st ring wit h t he ToSt r ing m et hod for display in a m essage box. Aft er
a user clears t he m essage box from t he screen, t he event procedure invokes t he
Nt hPow er m et hod in Class1. Again, t he m essage box argum ent conv ert s t he
num ber to a st ring for display. The last pair of MsgBox funct ions in t he event
procedure inv ok es t he Add2dbls2 m et hod. The first m essage box displays t he
Add2dbls2 m et hod out com e from it s base class im plem ent at ion ( in
Arit hm eticClass1) . The procedure concludes by invok ing t he sam e m et hod from
Class1. This result appearing in t he second m essage box w ill be t w ice as large as
it s pr edecessor . This is because different funct ion procedures im plem ent the
m et hod in each class. ( Cont rast the code for Add2dbls2 in t he t wo pr eceding class
list ings. )
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
’Sample to demonstrate basic inheritance to add a
’new method or override an existing one.
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click

’Hide unnecessary text controls.
Button2.Visible = False
Button3.Visible = False

’Instantiate objects based on the ArithmeticClass1
’and Class1 classes.
Dim arclass1 As New ArithmeticClass1()
Dim c1 As New Class1()

’Declare num1 and num2 variables and assign values
’to the variables based on text box entries.

Dim num1 As Double
Dim num2 As Double

num1 = CDbl(TextBox1.Text)
num2 = CDbl(TextBox2.Text)

’Set properties and invoke the Add2dbls method from
’the ArithmeticClass1 class.
arclass1.dblFirst = num1
arclass1.dblSecond = num2
MsgBox(arclass1.Add2dbls.ToString, , _
“Return from Add2dbls in ArithmeticClass1”)

’Invoke the NthPower method in Class1, which is a
’new method not in ArithmeticClass1.
MsgBox(c1.NthPower(num1, num2).ToString, , _
“Return from NthPower in Class1”)

’Invoke the Add2dbls2 method for the ArithmeticClass1
’and Class1 classes; the Add2dbls2 method in Class1
’overrides the Add2dbls2 method in ArithmeticClass1.
MsgBox(arclass1.Add2dbls2(num1, num2).ToString, , _
“Return from Add2dbls2 in ArithmeticClass1”)
MsgBox(c1.Add2dbls2(num1, num2).ToString, , _
“Return from Add2dbls2 in Class1”)

End Sub

Figur e 9-7 su m m ar izes the r esu lt s. On t he left is the form aft er I enter ed values
in bot h t ext box es and click ed Butt on1. Notice t hat Button2 and But t on3 aren’t

t here; that ’s because t he Butt on1_Click event procedure m ade t hem invisible on
t he form by set ting t heir Visible property t o False. The four m essage box es on t he
right display t he resu lt s in t he order t hat the But ton1_ Click ev ent procedur e
com put es t hem . The caption for each m essage box specifies t he source, including
t he m et hod and t he class, for t he displayed r esult . Not ice in particular t he last
t wo m essage boxes. These resu lt s in coordinat ion w it h t he list ing for the
Butt on1_Click event pr ocedure docum ent and confirm how you can override a
m et hod in a base class wit h a differ ent im plem ent at ion in a deriv ed class.
Figure 9 - 7 . By cre at ing in st an ce s for bot h a b ase class an d a derived
class, you can invoke m et h ods for both classe s, a nd som e of y ou r m e t hod
references in a de rived class can over ride t hose in a base cla ss.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

A Sha dow ing Sa m ple
As indicat ed in t he “ Overview of I nherit ance” sect ion, shadowing act s sim ilarly to
ov erriding but is m or e flexible. Th e sam ple for t his sect ion dem onst rat es t he use
of t he Shadows keyw ord. You can use t he Shadows keyword in a der ived class;
doing so doesn’t require any corresponding changes t o a base class. The sam ple
in the preceding sect ion required t he Overridable k eyword in t he base class for
the Ov errides keyword in t he derived class t o function properly .
The sam ple in t his sect ion uses t he TypeRef1 class t hat follows as t he base class.
Not ice t hat t he list ing for TypeRef1 includes a propert y procedure for a property
nam ed Value. The procedure includes bot h Get and Set clauses. This class is
sim ilar t o t he TypeRef sam ple presented earlier in t his ch apt er. The sole
dist inct ion bet ween TypeRef1 and TypeRef is t hat TypeRef1 com m ent ed out t he
New m et hod. Recall t hat in t he prior sam ple using TypeRef, the New m et hod was
helpful in set t ing an init ial value for a variable inst ant iat ed on t he class. Howev er,
when you use a class as t he base class for an I nherit s st atem ent, t he base class
cannot include a m et hod nam ed New. The inabilit y t o specify a New m et hod
wit hin t he class isn’t m aj or because an applicat ion can assign a value t o a

variable based on t he class im m ediat ely after inst antiat ing t he variable.
Public Class TypeRef1
Private intLocal

’Intialize Value to myInput -- not permissible in
’inherited class.
’Public Sub New(ByVal myInput As Integer)
’ Dim Value As Integer = myInput
’ MsgBox(Value.ToString, , “in new”)
’End Sub

’Read/Write property named Value.
Public Property Value() As Integer
Get
Return intLocal
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
End Get
Set(ByVal Value As Integer)
intLocal = Value
End Set
End Property

End Class

The shadow ing sam ple also relies on a second sam ple nam ed Class2. This class
inherit s Ty peRef1, so Class2 is a derived class wit h Ty peRef1 as it s base class.
Because TypeRef1 has j ust one property, Class2 m ust have a m em ber by t he
sam e nam e if it is t o sh adow t he property procedure in TypeRef1. I specifically
used t he term m em ber. This leav es open t he possibilit y of t he shadowing elem ent
being eit her a property or a m et hod. The only r equirem ent is that t he shadowing

elem ent hav e the sam e nam e as t he m em ber t hat it shadows. Alt hough t he
following list ing for Class2 dem onst rates t he use of t he Shadows keyw ord, t he
use of t his keyw ord is optional for im plem enting shadow ing. As y ou can see from
the following list ing, t he shadow ing version of t he propert y procedure for Value in
TypeRef1 adds 2 t o t he input . The original version of the property pr ocedure for
the Value propert y in TypeRef m erely echoes t he input .
Public Class Class2
’Class2 inherits from TypeRef1
Inherits TypeRef1

Private intLocal

’Read/Write property named Value in Class2
’shadows property with the same name in TypeRef1.
Public Shadows Property Value() As Integer
Get
Return intLocal
End Get
’New version adds 2 to initial input.
Set(ByVal Value As Integer)
intLocal = Value + 2
End Set
End Property

End Class

Click ing But t on2 on For m 1 in t he I nherit ingSam ple solut ion launches an event
procedure, which appears next . The procedure uses Butt on2 and Text Box1 ( along
wit h it s label). Therefore, t he event procedure st arts by hiding t he ot her cont rols
on the form . Next t he procedure convert s and copies the contents of Text Box1 t o

num 1, which t he procedur e declares as an I nt eger variable. This value t ype
specificat ion for num 1 is consist ent wit h t he Value propert y in TypeRef1 and
Class2. After st oring t he convert ed t ext box entr y in a variable for t he event
procedure, the procedure assigns t he value saved in num 1 t o t he Value propert y
in TypeRef1 and Class2. Finally, a pair of MsgBox funct ions echoes the quant it y in
the property.
’Sample to demonstrate shadowing with inheritance.
Private Sub Button2_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button2.Click

’Hide unnecessary text controls.
TextBox2.Visible = False
Label2.Visible = False
Button1.Visible = False
Button3.Visible = False

Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
’Instantiate objects based on the TypeRef1
’and Class2 classes.
Dim trclass1 As New TypeRef1()
Dim c2 As New Class2()

’Declare num1 variable and assign a value
’to the variable based on the text box’s entry.
Dim num1 As Integer

num1 = CInt(TextBox1.Text)

trclass1.Value = num1
c2.Value = num1


MsgBox(trclass1.Value.ToString, , _
“Return from Value property in TypeRef1”)
MsgBox(c2.Value.ToString, , _
“Return from Value property in Class2”)

End Sub

Figur e 9-8 sh ows t he shadow ing sam ple. On t he left panel, y ou see t he t ext box
and but ton for launch ing the event procedure. Not ice t hat t he t ext box cont ains
the value 3. On t he right side, you see t he tw o m essage boxes cont aining t he
echoed Value propert ies fr om Ty peRef1 and Class2. Alt hough t he input t o bot h
propert ies was t he sam e, t he out put is different because t he one expression in
Class2 is dist inct from it s count erpart for a shadowed pr opert y in TypeRef1.
Figur e 9 - 8 . Sh adow in g m ak es it e asie r for a de rived class t o ret ur n a
differe nt resu lt t ha n a prop er ty w it h th e sa m e na m e in a base cla ss.

An Overloading Sa m ple
Bot h overriding and sh adow ing are about doing m ore t hings w it h t he sam e
m et hods and propert ies. The Overloads k eyword is one m ore exam ple of a
keyw ord that sim plifies how y ou can do m ore w ith t he code in your sam ples. I n
essence, it allows you t o construct a set of procedur es all of w hich have the sam e
nam e but wit h different argum ent type specificat ions. When a user invokes a
m et hod based on t he set of procedures, t he .NET Fram ework autom at ically
det ect s the specific procedure that m at ches t he input dat a ty pe. You don’t hav e
t o use the Overloads keyword in an inherit ance cont ext , but it can work wit h
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
inherit ance. For sim plicit y, this sect ion dem onst rat es the use of t he Overloads
keyw ord wit hout involving inherit ance.
N ot e

You can also achieve overloading without the Ov erloads
keyword. Just m ak e sure all the procedure nam es are
identical, wit h different value t ype specifications for the
argum ents in each m em ber wit hin the set of procedures.
However, if you use t he Overloads keyword for at least one
m em ber in the set , you m ust use it for all m em bers.
The Class3 list ing shows a sim ple over loading sam ple. The class cont ains two
inst ances of the TenPercent OfI t funct ion procedure. These inst ances collect iv ely
im plem ent t he TenPercent OfI t m et hod for Class3. I f a user enters an argum ent
wit h a Double v alue t ype, such as 55.5, in t he TenPercent OfI t m et hod, Class3
responds by invoking the first funct ion procedure. This m ight happen if the user
inv okes t he m et hod from a dat abase wit h a colum n of Double values. On t he
ot her hand, w hen t he input for the TenPercent OfI t funct ion is a st ring, such as
55.5, Class3 autom at ically invokes the second funct ion procedure. This m ight
happen if an application passes a value direct ly from a t ext box t o t he class
m et hod. By using t he Overloads keyw ord in fr ont of bot h versions of t he funct ion,
the developer can leav e it t o t he .NET Fram ework t o figur e out wit h w hich specific
funct ion procedure t o im plem ent t he m et hod. As m ore pot ent ial dat a sources
becom e available, it is easy t o add a new copy of t he funct ion procedure wit h
different value type declarat ions for t he argum ent s.
Public Class Class3
Overloads Function TenPercentOfIt(ByVal It As Double) As Double
Return (It * 0.1)
End Function

Overloads Function TenPercentOfIt(ByVal It As String) As Double
Return (CDbl(It) * 0.1)
End Function
End Class


The follow ing Click event procedure for But t on3 dem onst rat es a t est of t he
ov erloading feat ure im plem ented in Class3. Aft er hiding the unnecessary cont rols
on the form , t he application inst ant iat es c3 as an inst ance of Class3. Next it
assigns a Double value of 55.5 t o num 1. The final pair of MsgBox funct ions
inv okes t he TenPercent OfI t m ethod in Class3 w it h t he num 1 Double value type or
a St ring value t ype based on t he cont ent s of Text Box1. Because t he r et urn from
the m et hod is a Double value, the argum ent for t he MsgBox funct ions invok es t he
ToSt ring m et hod on the ret urn value. The im portant point t o note is t hat even
though t he tw o MsgBox funct ions invoke the TenPercentOfI t m ethod w it h
different value types, t hey bot h invoke exact ly t he sam e m et hod wit h exact ly the
sam e syntax.
‘Sample to demonstrate overloading within a class.
Private Sub Button3_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button3.Click

’Hide unnecessary text controls.
TextBox2.Visible = False
Label2.Visible = False
Button1.Visible = False
Button2.Visible = False

’Instantiate Class3 with overloaded functions and declare
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
’a variable with a Double type for one of the functions.
Dim c3 As New Class3()
Dim num1 As Double

’Assign a value to the Double variable type and
’invoke one version of the overloaded function.
num1 = 55.5

MsgBox(c3.TenPercentOfIt(num1).ToString, , _
“Return based on a double input”)

’Invoke another version of the overloaded function with
’string input instead of numerical input.
MsgBox(c3.TenPercentOfIt(TextBox1.Text).ToString, , _
“Return based on a string input”)

End Sub

Figur e 9-9 confirm s t hat you can obtain ident ical results from the TenPercentOfI t
ov erloaded set of funct ions based on t wo different input value t ypes. The form on
the left shows 55.5 in a text box. This t ext box cont ains a St r ing value. The t w o
m essage boxes on t he right show ident ical ret urn values. How ever, t heir captions
confirm that t hey have different input value t ypes, and all our code did t o get t his
result was t o use t he Overloads k eyw ord. Som et im es Microsoft can m ake life so
sw eet !
Figure 9 - 9 . Overloa din g aut om at ica lly m at che s the proce dure invok ed t o
t he dat a t ype of th e argu m en t in a st at e m e nt callin g a set of ov erloade d
procedu re s.



Progra m m ing Event s
An event is a not ificat ion t hat som et hing happened. As Visual Basic program m ers,
you are well aware of event s from built -in object s, such as form s and but tons.
Many interm ediat e and advanced program m ers r egularly creat e cust om classes
that generat e cust om events w it h prior versions of Visual Basic. Adding ev ent s to
cust om classes allows obj ect s based on t he classes to conv ey inform at ion back to
the applications t hat inst ant iat e t he obj ect s.

Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Visual Basic .NET ret ains the event funct ionalit y from earlier versions while it
adds new capabilit ies as well, relat ed t o defining cu st om event handlers and
wor king with new sources for event s. This sect ion r eviews t he basics of ev ent
program m ing to provide a st andard back ground for m ore advanced topics,
including t he abilit y t o dynam ically define event handlers and new com ponent s
that can raise events.
Event Pr ogra m m ing Concept s
Even when working w it h built - in events for form s and t heir cont rols, it helps t o
have a basic underst anding of ev ent program m ing concept s, but a knowledge of
this t opic is essential when you develop events for cust om classes. Happily, a few
core concept s t hat ar e easy to grasp can enable you t o declare and m anage
cust om event s.
Event s hav e a source or a sender. This source is t he elem ent t hat sends out the
not ificat ion t hat an event happened. A class that you creat e can be a source. A
form class can be a source. For exam ple, Visual Basic raises t he Load event when
it opens a form inst ance. Sim ilarly, when a user click s a but ton on a form
inst ance, t his raises the Click event for t he but t on. For a source t o raise an event ,
two t hings m ust happen. First , t he event m ust be declared for the obj ect . You can
declare an Event st at em ent . Second, som e code inside t he class for t he obj ect
inst ance m ust invoke t he RaiseEvent st at em ent . The RaiseEvent st at em ent
triggers an event declared wit h t he Event st at em ent . You can raise an ev ent only
from the class in w hich it occurs. Therefore, a but t on cannot raise a Load event
for a form on which it resides. Sim ilarly, a derived class cannot use t he Raise-
Event st at em ent to t rigger an event declared in it s base class.
Event handlers process an event . Just because a class inst ance raises an ev ent
doesn’t m ean t hat an application has to acknowledge the event . Click ing a but ton
befor e y ou add a sub procedur e to process t he click has no effect . Th e sub
procedure is an event handler. Event handlers allow applications t o respond t o
events r aised by class inst ances. Visual Basic can aut om at ically cr eate em pt y

event handlers for t he Windows Form s and t heir cont rols. These em pty event
handlers are called st ubs. A st ub includes t he sub procedure declarat ion w it h a
nam e for the procedure, a list of argum ents, and a t erm inat ing st at em ent for the
procedure ( nam ely, End Sub) . St ubs also include a Handles clause t hat associat es
them wit h a class inst ance and an event nam e. You can det erm ine how your
applicat ion resp onds t o an event by placing your ow n code inside t he sub
procedure.
When you writ e event handlers for cust om classes, you m ay need t o cr eat e your
ow n st ub. I f you use t he Wit hEv ent s keyword when y ou inst ant iat e an obj ect
based on a class, you can use t he Visu al St udio developm ent environm ent t o
creat e a st ub for you autom at ically. When using t he Wit hEvent s keyw or d, you
m ust inst ant iat e your obj ect at t he m odule level. Wit hout t he Wit hEv ents
keyw ord, events don’t propagat e from a class t o an obj ect inst ance based on it.
Est ablish ing an associat ion bet ween an event handler and an event w it h the
Wit hEvent s keyw ord requir es you t o specify t he event handler at design t im e.
The AddHandler and Rem oveHandler st at em ent s allow you t o dy nam ically add
and rem ov e a handler for an event at r un tim e. You can also use t hese
st at em ents at design t im e. Wit h t hese t wo st at em ent s, you don’t have t o
inst ant iat e an obj ect using t he Wit hEvents keyw ord in order t o process event s
raised by t he obj ect . I n turn, t his m eans that you can inst ant iat e wit hin a
procedure or at t he m odule level. Recall t hat t he Wit hEvents k eyword requires
inst ant iat ion at t he m odule lev el. When using t he AddHandler st at em ent t o
associat e an event wit h an event handler, you m ust wr it e your own st ub for t he
event handler. I w ill dem onst rat e how t o do t his in a sam ple t hat illust rat es the
use of the AddHandler st at em ent.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Using Bu ilt - I n Form Events
There ar e a couple of w ays of m anaging built - in events wit h Windows Form s and
their cont rols from t he Window s Form s Designer. Double- click ing a form ’s capt ion
in the Window s Form s Designer opens the st ub for t he form ’s default event , the

Load event, in t he Code Edit or. This sam e technique works for t he cont rols on a
form . For exam ple, double- clicking a butt on on a form opens t he st ub for t he
butt on’s default event, a Click event . Aft er adding one or m ore cont rols on a
form , y ou can select any event for any cont rol in t he Code Edit or. Choose the
cont rol nam e from the Class Nam e drop-down list at t he upper left of t he Code
Edit or, and choose the event nam e from t he Met hod Nam e list at the right. Aft er
you click an event for t he cont rol, a st ub for t he event pr ocedure appears
autom at ically. To display a nondefault event for t he form , select ( Base Class
Event s) from the Class Nam e list and t hen ch oose a desired event fr om t he
Met hod Nam e list .
I f you search t hrough t he event s for a form or any of the contr ols on a form , you
will quickly discover an exceedingly large array of event s. Alt hough t he large
num ber of events is useful for fine- grained cont rol ov er the operat ion of an
applicat ion, it m ay be difficult for som e program m ers t o discern t he order of the
events so t hey can know which one to use. The follow ing excerpt fr om the Code
Edit or for Form 4 in t he Event sSam ples solution dem onst rat es a st rat er gy for
tracking event s. Within each ev ent procedur e is a MsgBox funct ion indicating
which ev ent generat ed t he current m essage box in an applicat ion. For exam ple,
the m essage box for t he form Load event fir es befor e Form 4 is displayed. When
you click t he form ’s Close butt on, y ou will not ice t hat the Closing ev ent fir es prior
to the Closed ev ent . See t he follow ing not e for det ailed inst ruct ions on m aking
Form 4 t he st art up object for t he Event sSam ples solut ion.
N ot e
A Windows application st art s by default wit h Form 1, which is
the obj ect t hat Visual St udio .NET m akes after opening a
Windows application for design. By default , the Windows
application opens t o this obj ect when you run the solut ion.
However, you can choose another object for a Windows
application t o open when it st art s to run. Right - click the
solution’s nam e in Solut ion Explorer, and choose Propert ies

to open the Property Pages dialog box for the solution. Use
the Start up Object drop- down list t o select another obj ect .
For ex am ple, select ing Form 4 will cause this form t o open
init ially when a user chooses to run the solut ion.
Event s som et im es fire so quick ly t hat m essage boxes can pile up and m ake
discovering their order confusing. I n cases like t his, you can som et im es set a
propert y for an object on t he form — and t hus change it s appearance— t o help
indicat e t he order of event s. The procedures for the MouseEnt er, MouseHover,
and MouseLeave event s from But ton1 dem onst rat e t his appr oach . These event
procedures change the Back Color pr operty for Button1. I nit ially posit ioning t he
m ouse over But t on1 changes t he Back Color propert y from it s default sett ing t o
Syst em .Drawing.Color.Cyan. Because Visual St udio autom at ically cr eat es a
reference t o t he Syst em .Drawing nam espace when it init ializes a Windows
applicat ion, you can abbreviat e t he set ting t o Color.Cyan. Leaving the m ouse
ov er a but t on event ually invok es t he MouseHover event, which ch anges the
BackColor set t ing t o Sy st em .Draw ing.Color.Red. Rem oving t he m ouse from ov er
the but ton rest ores the default Back Color set t ing of
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Syst em .Drawing.Sy st em Colors. Cont rol. Click ing But ton1 displays a m essage box
and shifts the focus from Form 4 t o the m essage box. This Butt on1_Click event is
ort hogonal to t he MouseEnt er and MouseHover events in that clicking t he butt on
can int errupt t he tr ansit ion from t he MouseEnt er event t o t he MouseHover event.
Private Sub Form4_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
MsgBox(“Just before I load.”)
End Sub

Private Sub Form4_Closing(ByVal sender As Object, _
ByVal e As System.ComponentModel.CancelEventArgs) _
Handles MyBase.Closing

MsgBox(“From Closing event.”)
End Sub

Private Sub Form4_Closed(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles MyBase.Closed
MsgBox(“From Closed event.”)
End Sub

Private Sub Button1_MouseEnter(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Button1.MouseEnter
Me.Button1.BackColor = System.Drawing.Color.Cyan
End Sub

Private Sub Button1_MouseHover(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Button1.MouseHover
Me.Button1.BackColor = System.Drawing.Color.Red
End Sub

Private Sub Button1_MouseLeave(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Button1.MouseLeave
Me.Button1.BackColor = System.Drawing.SystemColors.Control
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
MsgBox(“You clicked Button1”)
End Sub

Before proceeding t o a second sam ple, it m ay be useful t o review t he sy ntax for
an event procedure. Not ice t hat t hey are sub procedures m eant for operat ion in

the cur rent m odule, as specified by t he use of t he Privat e keyw ord. Privat e m arks
the event procedure for exclusive use in the cur rent m odule. The argum ents list
can offer you a way of changing t he operation of t he event procedure. The nex t
sam ple dem onst rat es the use of an event argum ent t o control t he behavior of t he
Closing event. Aft er t he argum ent list , t he Handles clause sp ecifies t he obj ect and
event t hat t he sub procedure handles. You cont rol t he operat ion of t he event
procedure by placing cust om code between t he Sub and End Sub st at em ent s.
The next select ion of ev ent procedures show s a pair of procedures for cont rolling
how a user can close a form . When a user chooses to close a form by clicking t he
form ’s Close but t on, t he application fires t he Closing event . This event occurs
befor e t he form closes. By set t ing t he Cancel event argum ent t o True in t he
Closing event, you can block t he Close event fr om occurring ( nam ely , t he form
will rem ain open) . The default value for t he Cancel ev ent argum ent is False. You
can use t his featur e t o perform ot her act ions j ust before closing a form . For
exam ple, you can disp lay a m essage block ing t he operat ion of t he form ’s Close
butt on and inst ruct ing t he user t o click a but t on that launches t he ot her act ions
you want done before invoking t he form ’s Close m et hod. Because t he Close
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
m et hod raises t he Closing event , y ou m ust const ruct t he form ’s Closing ev ent
procedure t o optionally by pass set t ing t he Cancel argum ent to True.
The follow ing code excerpt for For m 5 dem onst rat es how t o disable a form ’s Close
butt on and redirect t he user t o a but t on on t he form . Th e solut ion uses t wo
events. First t he Form 5 _Closing event procedure blocks t he Close event from
occurring by sett ing t he Cancel ev ent argum ent to bolDisableClose. The m odule-
level declarat ion for bolDisableClose set s the variable’s default value to True. The
I f…Then…Else st at em ent in t he pr ocedure displays a m essage box direct ing t he
user to click But t on1 t o close t he form . Th e Click event pr ocedure for But t on1
set s bolDisableClose t o False befor e inv ok ing the Close m et hod for the Me
keyw ord that refers back t o t he current form , w hich is Form 5 in t his case. The
inv ocation of t he Close m et hod, in t urn, launches the Form 5_Closing event

procedure, but t his t im e t he procedure t akes a different pat h t hrough it s
I f…Then…Else st at em ent because of t he new value for the bolDisableClose
variable.
‘bolDisableClose controls Cancel argument.
Dim bolDisableClose As Boolean = True

‘Conditionally block close of form.
Private Sub Form5_Closing(ByVal sender As Object, _
ByVal e As System.ComponentModel.CancelEventArgs) _
Handles MyBase.Closing
If bolDisableClose Then
e.Cancel = bolDisableClose
MsgBox(“Click Button1 to close form.", , _
“After clicking Close button”)
Else
MsgBox(“From form’s Closing event.", , _
“After clicking Button1”)
End If
End Sub

‘Enable form close by setting bolDisableClose to False.
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
’Perform any other necessary actions before closing Form5.
bolDisableClose = False
Me.Close()
End Sub

Pr ocessing Ev e nt s Using t he W it hEvents Keyw or d
The ev ent processing t echniques for this sam ple and t he next t wo all em anat e

from Form 1 in t he Event sSam ple solut ion. Fig ure 9- 10 shows t his form t wo
different ways. At left is t he form as it looks in t he Window s Form Designer— in
design view . At right is t he form as it appears when you run the
Event sSam ple.ex e file. The differences bet ween t he tw o views of t he form are t he
result of t he Form 1_Load event pr ocedure. (See the follow ing sam ple.) This
procedure adds t ext t o som e controls and clears it from ot her controls. I n
addit ion, it form at s t he alignm ent for t he label and t ext cont rols as well as resizes
the default Width propert y set t ing for t he but ton controls. This t ransform at ion
dem onst rates a use for t he form Load event t hat m akes it easy to spot changes
to the default set t ings for the contr ols on a form . I f you need to duplicate form
set tings acr oss m ult iple form s or syst em at ically change sett ings acr oss m ult iple
form s, t his kind of procedure can prove especially conv enient.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Figur e 9 - 1 0 . Using a form Load eve nt proce dur e to d ocu m en t your form at
se tt ings for a form can h elp in docum en ting those se tt ings an d applyin g
t hose set t ings in a un ifor m w a y to m ult iple form s in a n applica t ion .

Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
’Set selected properties for form controls at load time.

’Set Text and Width properties for Button1.
Button1.Text = “Add"
Button1.Width = 90

’Set TextAlign property for text boxes.
TextBox1.TextAlign = HorizontalAlignment.Right
TextBox2.TextAlign = HorizontalAlignment.Right
TextBox3.TextAlign = HorizontalAlignment.Right


’Set Text property for labels.
TextBox1.Text = “"
TextBox2.Text = “"
TextBox3.Text = “"

’Set TextAlign align property for labels.
Label1.TextAlign = ContentAlignment.MiddleRight
Label2.TextAlign = ContentAlignment.MiddleRight
Label3.TextAlign = ContentAlignment.MiddleRight

’Set Text property for text boxes.
Label1.Text = “Byte1"
Label2.Text = “Byte2"
Label3.Text = “Sum"

’Set Text and Width properties for Button2.
Button2.Text = “Open Form2"
Button2.Width = 90

’Set Text and Width properties for Button3.
Button3.Text = “Open Form3"
Button3.Width = 90

’Set Text and Width properties for Button4.
Button4.Text = “Close App"
Button4.Width = 90

End Sub
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.


The form at right in Figure 9 -10 per m its a user t o ent er t wo Byt e value type
quant it ies in t he Byt e1 and Byt e2 t ext box es. When a user click s t he Add butt on,
the form ret urns t he tot al of t he t w o quant it ies in t he Sum t ext box . I f t he sum
happens t o exceed 255, which is the m ax im um legit im at e Byt e value, t he
applicat ion displays a m essage box wit h a r em inder of t he problem . Because t he
applicat ion com put es t he sum as a Decim al value t ype, ret urn values great er t han
the m ax im um don’t generat e a run-t im e error. How ever, you can raise an ev ent
that ident ifies sum s greater t han 255. I f a user ent ers a value gr eat er t han 255 in
eit her the Byt e1 or Byt e2 t ext box, Visual Basic raises an error because t he Add
butt on’s Click event procedure uses the CByt e funct ion t o convert t he t ext box
values t o Byt e dat a t ypes.
Before rev iewing t he code behind Form 1 t hat m anages t he operat ion of t he form ,
it w ill be useful t o exam ine t he code list ing for t he Byt eAr it hm et ic class. Form 1
relies on t he class t o save t he values in t he two input t ext boxes, com pute the
sum , and raise t he event. The class list ing includes an event declarat ion, a Privat e
st at em ent for declaring t wo int ernal var iables, t wo propert y pr ocedures, and a
funct ion procedure. The Public accessibilit y qualifier for t he event declaration at
the t op of t he list ing m akes t he ev ent available t hr oughout t he Event sSam ple
solution assem bly. I f By t eArit hm et ic exist ed as a st and- alone class proj ect wit h a
.dll ext ension, the Public declarat ion would perm it the accessibilit y of t he event in
ot her pr oj ect s t hat reference t he .dll file.
The propert y pr ocedures nam ed Byt e1 and Byt e2 can accept convert ed dat a from
text boxes on Form 1. The class represents t hese propert y set tings int ernally wit h
the byt1 and byt 2 variables, which are declared direct ly below t he event
declaration. A funct ion procedure, Add2byte, in By teAr it hm et ic com put es t he sum
and condit ionally raises an error. This procedure com put es the sum of t he two
types as a Decim al value t ype, w hich it saves in t he m ysum variable. This design
feat ur e av oids the pot ent ial of a run-t im e er ror from a sum that exceeds t he Byte
value lim it . However, Add2byt e also checks for sum s t hat exceed 255. When it
finds a sum t hat exceeds t he m axim um Byt e value, it raises t he TooHigh event

and ret urns as an event argum ent t he m ysum variable value. The Add2byte
procedure list ing concludes wit h a Ret urn st at em ent that passes back t he value of
m ysum t o t he procedure t hat invoked t he Byt eAr it hm et ic class inst ance.
Public Class ByteArithmetic
’You need to declare an event before you can raise it.
Public Event TooHigh(ByVal ReturnValue As Decimal)

’Local variables for property values.
Private byt1, byt2 As Decimal

’Property procedures for Byte1 and Byte2.
Public Property Byte1() As Byte
Get
Return byt1
End Get
Set(ByVal Value As Byte)
byt1 = Value
End Set
End Property

Public Property Byte2() As Byte
Get
Return byt2
End Get
Set(ByVal Value As Byte)
byt2 = Value
End Set
End Property
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.


’Function procedure for the Add2byte method.
Function Add2byte() As Decimal
Dim mysum As Decimal

’Compute mysum.
mysum = byt1 + byt2

’Raise event if sum is too high.
If mysum > 255 Then RaiseEvent TooHigh(mysum)

Return mysum

End Function

End Class

The next code excerpt shows t he code behind Form 1 t hat works w it h t he
Byt eAr it hm et ic class. The list ing st art s wit h a declarat ion of an inst ance nam ed ba
for t he Byt eArit hm etic class. There are t w o especially im port ant feat ures of t his
declaration. First , t he declarat ion includes t he Wit hEvents keyw ord. Th is allows
Form 1 t o process event s raised by ba. Second, the declarat ion occurs at t he
m odule level. Th is is m andat ory when you use t he Wit hEvents keyw ord in the
declaration for a class inst ance.
I generat ed the st ub for the Butt on1_Click event procedure by double- click ing t he
cont rol in the Window s Form s Designer. The event procedure is generated by t he
double click on the cont rol because Click is t he but ton’s default event. Wit hin the
Click event are two block s of code. First t he procedure convert s t he t ext box
ent r ies w it h t he CByt e funct ion t o Byt e value ty pes from t heir nat ive St ring value
types. Second t he procedure invokes t he Add2byte m et hod for the ba class
inst ance and st ores the ret ur n value as a st ring in Text Box 3.

The second procedure is the event handler for t he TooHigh event from the ba
class inst ance. I n t he Code Edit or for Form 1, you can cr eat e t he st ub for t he
event procedure aut om at ically by choosing ba in t he Class Nam e box and click ing
TooHigh in t he Met hod Nam e box t o its right . Aft er Visual St udio created t he st ub,
I had t o add j ust one line of code, which present s a m essage box rem inding t he
user that t he sum is t oo large for a legit im at e Byt e value. The m essage box also
cont ains t he value ret urned as t he sum .
‘WithEvents keyword must apply to module-level declaration;
‘the keyword permits events to pass from event source (ByteArithmetic
).
Private WithEvents ba As New ByteArithmetic()

Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click

’Copy converted text box entries to Byte1 and
’Byte2 properties in ByteArithmetic class.
ba.Byte1 = CByte(TextBox1.Text)
ba.Byte2 = CByte(TextBox2.Text)

’Display result of addition in TextBox3.
TextBox3.Text = (ba.Add2byte).ToString()

End Sub


’Handles clause in event sub stub requires a WithEvents keyword
’in variable declaration for event source (ByteArithmetic).
Private Sub ba_TooHigh(ByVal ReturnValue _
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

As Decimal) Handles ba.TooHigh

’Display event message.
MsgBox(“Sum of “ & ReturnValue & “
too large for byte value.”)

End Sub

Figur e 9-11 sh ow s the out com e of t rying t o add 4 and 252 w it h t he applicat ion
det ailed in t he preceding tw o code segm ent s. Each quant it y alone is a legit im at e
Byt e value. However, their sum exceeds t he m axim um Byt e value. Therefore, t he
applicat ion displays the m essage box shown at t he left of Figure 9-11 befor e
populat ing Text Box3 w it h t he ret urn value from the Byt eAr it hm et ic inst ance.
Form 1 appears on t he right side of Figure 9-11, wit h t he t wo input values and
their sum . To properly close the solut ion, a user m ust click t he Close App but t on.
Figur e 9 - 1 1 . You ca n use a cu st om even t to display a m essa ge box.

Pr ocessing Ev e nt s w it h t he AddHa ndler St a t e m e nt
Below the t hird t ext box in Figur e 9-11 is t he Open Form 2 but ton. Click ing t his
butt on opens a second form that dem onst rat es how t o use the AddHandler
st at em ent t o process a raised event. Form 2 has j ust t wo but tons. That ’s because
this form uses t he t ext boxes on Form 1 t o display input and out put from t he
inst ance of By t eAr it hm et ic t hat it declares. Ther efore, anot her benefit of t his
sam ple is t hat it reveals how t o pass values back and fort h bet ween t wo form s.
The only way t hat t he applicat ion will open Form 2 is by a click t o the Open For m 2
butt on on For m 1. The application’s logic requires t hat t her e be num eric ent ries in
the Byt e1 and By t e2 t ext boxes befor e t he click. Failing to populat e t he t ext
boxes wit h appropriat e values before t he click will generat e a run-t im e error . The
Click event procedur e for But t on2 on Form 1 follows. Not ice t hat the But ton2_Click
event procedure com m ences by inst antiat ing an inst ance of Form 2 and

referencing it wit h t he frm Form 2 variable. Wit h t he frm Form 2 var iable, t he event
procedure can then access elem ents in t he code behind Form 2. As a su bsequent
list ing shows, two of t hese elem ents ar e variables nam ed frm 2byt e1 and
frm 2byt e2. The assignm ent st at em ents in the Click event procedure dem onst rat e
the sy nt ax for copying convert ed text box values from one form ( For m 1) t o
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

×