Programming Microsoft SQL Server 2000 with Microsoft Visual Basic .Net - P6

Chia sẻ: Thanh Cong | Ngày: | Loại File: PDF | Số trang:50

0
68
lượt xem
11
download

Programming Microsoft SQL Server 2000 with Microsoft Visual Basic .Net - P6

Mô tả tài liệu
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

Tham khảo tài liệu 'programming microsoft sql server 2000 with microsoft visual basic .net - p6', công nghệ thông tin, cơ sở dữ liệu phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả

Chủ đề:
Lưu

Nội dung Text: Programming Microsoft SQL Server 2000 with Microsoft Visual Basic .Net - P6

  1. End Sub Going from a hexadecim al value t o a Long value is m or e com plicat ed for a couple of reasons. First , t her e is no built - in funct ion. Second, hexadecim al num bers need t o be convert ed on a charact er - by - charact er basis t hat reflect s t he char act er’s posit ion in t he hexadecim al num ber. This t ask is furt her com plicat ed by t hat fact t hat charact ers go out side t he decim al range of 0 t hrough 9 t o t he hex adecim al range of 0 t hrough F. The follow ing sam ple per for m s a check t o v er ify t hat t he hexadecim al st r ing value doesn’t exceed t he m axim um Long value. The hex represent at 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 hex adecim al value, t he Convert Hex ToLng pr ocedur e st art s a loop t hat it erat es t hr ough successiv e charact ers in t he hexadecim al num ber. St art ing at t he far r ight charact er , t he loop evaluat es each charact er. The evaluat ion m ult iplies t he hex charact er’s decim al v alue by a power of 16. The pow ers range in value fr om 0 for t he far right charact er t o up t o 15 for t he sixt eent h hex charact er ( if t her e is one) . When t he Conv ert HexToLng procedur e finishes looping t hr ough t he charact er s in t he hexadecim al num ber, t he pr ocedur e present s a m essage box w it 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.
  2. 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 nh e r it in g Cla sse s Classes ar e gr eat 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 t ing one class inherit t he propert ies, m et hods, and event s of anot her class. I nher it ance for cust om classes is new t o Visual Basic program m ers w it h Visual Basic .NET. This sect ion begins w it 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 t hat dem onst rat e t he synt ax for im plem ent ing inher it ance w it h different key words. At t he sect ion’s close, you will discover a discussion of ov er loading. This feat ure can m ak e one m et hod or propert y w it hin a class easily accept m any different t ypes of value input s. I nst ead of building capabilit ies int o applicat ions by lay ering one class on t op of anot her or m anually coding a class t o t est m ult iple value t ypes and t hen r espond appropriat ely t o t he input value t ype, t he Over loads keyword expands t he capabilit ies of a single class. I cover t he Ov er loads keyw ord in t his sect ion because of it s r esem blance t o t he Ov er r iding keyword— one of t he k eyw ords for m anaging inher it ance— and because Ov er loads widens t he capabilit ies of a class m uch as inherit ance can. Ov e r vie w of I nh e r it a n ce Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  3. I nher it ance is for classes. I t let s one class inher it t he pr opert ies, m et hods, and ev ent s 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 Ev ent s” sect ion lat er in t his chapt er for m or e on m anaging class event s.) When Class B inher it s Class A, Class B can offer t he sam e m et hods, propert ies, and event s of Class A. I n addit ion, Class B can offer new pr opert ies and m et hods as well as m odified versions of t he pr opert ies and m et hods in Class A. Visual Basic dev elopers didn’t hav e t his capabilit y 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 lear n som e new concept s and sy nt ax t o t ak e adv ant age of inherit ance. We can st art our new inherit ance vocabulary by r efer r ing t o t he inher it ed class as t he base class. The class t hat inher it s a base class is a derived class. When one class inher it s fr om anot her class, t he der ived class m ust cont ain a declarat ion st at ing from which class it inherit s propert ies and m et hods. Visual Basic .NET uses an I nherit s st at em ent t o m ake t he declarat ion. The I nher it s st at em ent t akes as it s argum ent t he nam e of t he base class. You can have j ust one class nam e as t he argum ent for I nher it s. Therefore, a class can inher it fr om at m ost one ot her class at a t im e. I f t he der iv ed class adds any new m et hods, it can offer t he m et hods of t he base class along w it h it s ow n new m et hods. I n addit ion t o offer ing new m et hods, t he deriv ed class can offer m odified im plem ent at ions of one or m ore m et hods from t he base class. Anot her new inherit ance t er m in Visual Basic .NET is polym or phism . I t describes t he abilit y of a der iv ed class t o change t he im plem ent at ion of a base class m em ber, such as a propert y or a m et hod. An applicat ion can inst ant iat e inst ances for a der ived class and it s base class. I n t his way, t he applicat ion can inv ok e an unm odified m et hod from a base class and an updat ed m et hod w it h t he sam e nam e from a der iv ed class. I n order for Visual Basic .NET t o m odify a base class m et hod in a der iv ed class, your class m et hods r equir e special k eyw ords. First , t he base class m ust m ark t he m et hod nam e w it h t he Over ridable key word, such as in t he 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, y ou need a cor responding k eyw ord, Over rides, in t he 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 ent at ion y ou want t o change. For exam ple Class MyDerivedClass Inherits MyBaseClass Overrides Function One () As Double ’New code for returning a value. End Function End Class As y ou 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 ov er r idden in der iv ed classes wit h t he Over ridable key word. You m ust also sy nchr onize m et hod nam es bet w een t he base and der iv ed classes. The m et hod nam es w it 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 w een 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 der ived classes has a special m eaning t hat we will consider short ly . I n order for a der iv ed class t o refer back t o a m et hod or pr opert y in a base class, you need t o use t he special My Base k eyw ord. You w ill t ypically use t he My Base keyw ord wit hin a funct ion in a der iv ed class t hat ov err ides an ident ically nam ed Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  4. funct ion in a base class. You can also use t he MyBase k eyw ord t o set and get propert y values for a base class from a der iv ed class. Then you can use t he My Base k ey word t o invoke a m et hod w it h t he v alues t hat y ou passed t o t he base class. For exam ple, MyBase.One() in a deriv ed class invokes t he One m et hod in t he base class. The Shadows keyword can apply t o propert ies and m et hods in a der iv ed class. This k eyw ord essent ially blocks t he availabilit y of ident ically 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 ov er an ident ically nam ed pr opert y or m et hod in a base class. The Shadows keyword is m ore flex ible and pow er ful t han t he Ov erridable/ Ov er r ides keywords. For exam ple, t he Ov er ridable/ Ov er r ides keyw ords apply only t o m et hods im plem ent ed wit h sub procedures or funct ion procedur es. The Shadows keyw ord apples t o m et hods as well as pr opert ies. I n addit ion, you can shadow a m et hod in a base class wit h a pr opert y in a der iv ed class. The Shadows k ey word rem oves t he dependence of a der iv ed class on an ident ically nam ed obj ect in a base class. This insulat 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 der ived class. The Overr idable/ Ov errides k eywords don’t offer t his prot ect ion for a der ived class from changes m ade in a base class. The Ov er loads keyword isn’t st rict ly an inher it ance t opic, but t his k eyw ord pert ains t o classes, and it s nam e is sim ilar t o Ov er r ides. I n addit ion, using t he Over loads key word on a funct ion pr ocedur e, sub procedure, or propert y procedur e can alt er t he behav ior of t he pr ocedure. How ev er , t he Ov erloads 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 Over loads k eyword is t o enable m ult iple v ersions of a funct ion procedur e t o operat e as one. Each funct ion pr ocedur e in a set of ov erloaded funct ion pr ocedur es has t he sam e nam e. Howev er , t he argum ent t ypes change for each funct ion procedur e w it hin a set . Ther efor e, one v ersion of a m et hod can accept a st ring argum ent , but anot her v ersion can accept a double dat a t ype as an ar- gum ent . The . NET Fram ework w ill aut om at ically inv ok e t he r ight funct ion procedur e based on an input ’s dat a t ype! That ’s t he power of t he Over loads keyw ord. An I n h e r it in g a n d Ove r r iding Sa m ple Any Windows applicat ion apply ing class inher it ance w ill cont ain at least t hr ee unit s 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 ant iat e one or m or e classes and inv ok e t he m et hods or m anipulat e t he pr ocedur es in t he der iv ed class or it s base class. I n a Windows applicat ion, y ou can inst ant iat e classes and m anipulat e t he inst ances from event procedures for but t ons on a for m . One or m ore t ext boxes on a form can prov ide v ehicles for users t o specify input values as argum ent s for m et hods and propert ies. The sam ple for t his sect ion is a Windows applicat ion t hat includes a for m ( Form 1) wit h m ult iple but t ons and t ex t box es for users t o m anipulat e. The first sam ple uses But t on1 along w it h Text Box1 and Text Box 2. Click ing But t on1 launches an ev ent procedure t hat inst ant iat es a base class, Ar it hm et icClass1, and a der ived class, Class1. The procedur e m anipulat es t hese class inst ances in various way s wit h input fr om t he ent r ies in Text Box1 and Tex t Box2. I will det ail t he m anipulat ions by describing t he But t on1_Click ev ent pr ocedur e aft er discussing t he code in t he Arit hm et icClass1 and Class1 classes. N ot e The sam ple for t his sect ion and t he nex t t wo sect ions dem onst r at ing inherit ance wit h Visual Basic .NET all use t he Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  5. sam e solut ion, I nherit ingSam ple. You can double- click I nherit ingSam ple.sln in Windows Ex plorer t o open t he solut ion in Visual St udio. To r un t he applicat ion fr om Windows Explor er, invoke t he I nherit ingSam ple1.exe file. The filenam e for t he .ex e file ret ains t he original nam e for t he solut ion. Ar it hm et icClass1 is a variat ion of t he st and- alone class in t he Ar it hm et icClass proj ect discussed in t he “Cr eat ing 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 specify ing t wo w r it e- only pr opert ies. Ar it hm et icClass1 also specifies t wo m et hods— bot h based on funct ion pr ocedur es. The Add2dbls m et hod follows dir ect ly fr om t he Arit hm et icClass present ed earlier in t his chapt er; t he m et hod adds t wo values w it h a Double value t ype. A sub procedur e im plem ent s t his m et hod. The input for t he funct ion pr ocedur e is fr om t he Writ eOnly pr opert ies, which specify t he double values t o add. A funct ion procedur e im plem ent s t he second m et hod, Add2dbls2, in Ar it hm et icClass1. Using argum ent s for t he funct ion pr ocedur e elim inat es t he need t o r ely on propert ies t o specify t he values t o add. The Ov err idable k ey word appears at t he st art of t he Add2dbls2 m et hod specificat ion. This m eans t hat anot her class inher it ing Ar it hm et icClass1 can ov er r 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 t hr ee m aj or sect ions; t he full list ing for t he class appears next . The first sect ion inher it s Ar it hm et icClass1. The I nher it s st at em ent m akes Class1 a der iv ed class wit h Ar it hm et icClass1 as it s base class. Class1 can reference all t he propert ies and m et hods of Ar it hm et icClass1 t hr ough t he My Base keyw ord. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  6. 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 v alue of t he base v alue t o a power, such as 2 3 equaling 8. This funct ion accept s ar gum ent s for t he base and power var iable 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 Ar it hm et icClass1.) The Over rides k eyw ord at t he beginning of t he m et hod specificat ion in Class1 along w it h t he m at ching Over ridable key word for t he sam e m et hod nam e in Ar it hm et icClass1 perm it s t he overr ide. 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 My Base k ey word facilit at es t he r efer ence back t o t he base class. The ar gum ent s passed t o t he Add2dbls2 m et hod in Class1 t ransfer t o t he base class t hrough t he argum ent s in t he expression cont aining t he My Base k ey word. 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 But t on1, w hich appears nex t , begins by hiding som e cont rols t hat ar en’t necessary for t his use of t he form . Then t he ev ent pr ocedur e inst ant iat es Ar it hm et icClass1 as t he arclass1 variable and Class1 as t he c1 variable. The pr ocedur e uses t wo t ext boxes on t he form so t hat users can specify double values for t he m et hods in t he classes. Because t he t ext box values requir e conv ersion t o m ak e 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 w o variables w it h a Double value specificat ion. Aft er concluding t he pr eceding pr elim inary st eps, t he event procedur e st art s com put ing and display ing result s. I nit ially t he procedure passes t he Double values saved in num 1 and num 2 t o t he propert y pr ocedur es assigning values t o t he dblFirst and dblSecond propert ies in Arit hm et icClass1. Next t he procedur e inv okes t he Add2dbls m et hod w it hin t he Arit hm et icClass1 and co- nv ert s t he out com e t o a st r ing 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 invok es 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 t o a st r ing for display . The last pair of MsgBox funct ions in t he ev ent procedur e inv ok es t he Add2dbls2 m et hod. The first m essage box display s t he Add2dbls2 m et hod out com e from it s base class im plem ent at ion ( in Ar it hm et icClass1) . The procedure concludes by inv ok 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 pr ocedur es im plem ent t he m et hod in each class. ( Cont rast t he 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.
  7. ’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 sum m ar izes t he r esult s. On t he left is t he form aft er I ent er ed values in bot h t ext box es and clicked But t on1. Not ice t hat But t on2 and But t on3 ar en’t t here; t hat ’s because t he But t on1_Click ev ent procedur e m ade t hem invisible on t he form by set t ing t heir Visible pr opert y t o False. The four m essage box es on t he right display t he r esult s in t he order t hat t he But t on1_Click ev ent procedur e com put es t hem . The capt ion 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 part icular t he last t wo m essage box es. These result s in coordinat ion w it h t he list ing for t he But t on1_Click ev ent pr ocedur e docum ent and confirm how you can overr ide a m et hod in a base class wit h a differ ent im plem ent at ion in a der iv ed class. Figu re 9 - 7 . By cr e a t in g in st a n ce s for bot h a b ase class an d a de rive d class, you ca n in vok e m et h od s for b ot h cla sse s, a n d som e of you r m e t h od r efe re n ce s in a d e rived cla ss ca n over r ide t h ose in a ba se cla ss. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  8. A Sha dow in g Sa m ple As indicat ed in t he “ Ov erv iew of I nher it ance” sect ion, shadow ing act s sim ilar ly t o ov err iding but is m or e flex ible. The sam ple for t his sect ion dem onst rat es t he use of t he Shadows k eyw or d. You can use t he Shadows keyw ord in a der iv ed class; doing so doesn’t require any corresponding changes t o a base class. The sam ple in t he pr eceding sect ion required t he Over ridable k eyw ord in t he base class for t he Ov errides keyword in t he der iv ed class t o funct ion pr oper ly . 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 propert y nam ed Value. The pr ocedur e includes bot h Get and Set clauses. This class is sim ilar t o t he TypeRef sam ple present ed ear lier in t his chapt er. The sole dist inct ion bet w een 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, t he New m et hod was helpful in set t ing an init ial value for a var iable inst ant iat ed on t he class. Howev er, when y ou use a class as t he base class for an I nherit s st at em 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 aft er inst ant iat ing t he v ar iable. 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.
  9. 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 TypeRef1, so Class2 is a der iv ed class wit h TypeRef1 as it s base class. Because TypeRef1 has j ust one pr opert y, Class2 m ust have a m em ber by t he sam e nam e if it is t o shadow t he pr opert y procedur e in TypeRef1. I specifically used t he t erm m em ber. This leav es open t he possibilit y of t he shadow ing elem ent being eit her a propert y or a m et hod. The only r equirem ent is t hat t he shadow ing elem ent hav e t he sam e nam e as t he m em ber t hat it shadows. Alt hough t he follow ing list ing for Class2 dem onst rat es t he use of t he Shadows k eyw ord, t he use of t his keyw ord is opt ional for im plem ent ing shadow ing. As y ou can see from t he follow ing list ing, t he shadow ing v ersion of t he pr opert y procedure for Value in Ty peRef1 adds 2 t o t he input . The or iginal v ersion of t he propert y pr ocedur e for t he Value propert y in Ty peRef 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 ev ent procedur e, w hich appears next . The pr ocedure uses But t on2 and Text Box1 ( along wit h it s label) . Therefore, t he event procedure st art s by hiding t he ot her cont rols on t he form . Next t he procedur e conv ert s and copies t he cont ent s of Text Box1 t o num 1, which t he pr ocedur e declares as an I nt eger variable. This value t ype specificat ion for num 1 is consist ent w it h t he Value pr opert y in TypeRef1 and Class2. Aft er st oring t he conv ert ed t ext box ent r y in a v ar iable for t he event procedur e, t he procedur e 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 t he quant it y in t he propert y. ’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.
  10. ’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 shows t he shadow ing sam ple. On t he left panel, y ou see t he t ext box and but t on for launching t he event procedure. Not ice t hat t he t ext box cont ains t he value 3. On t he r ight side, y ou see t he t w o m essage box es cont aining t he echoed Value pr opert ies fr om TypeRef1 and Class2. Alt hough t he input t o bot h propert ies was t he sam e, t he out put is differ ent because t he one expression in Class2 is dist inct from it s count erpart for a shadowed pr opert y in TypeRef1. Figu r e 9 - 8 . Sh ad ow in g m ak e s it e a sie r for a de rive d cla ss t o re t u r n a d iffer e n t r esu lt t h a n a pr op er t y w it h t h e sam e n a m e in a ba se cla ss. An Ov e r loa din g Sa m ple Bot h ov err iding and shadow ing are about doing m or e t hings w it h t he sam e m et hods and pr opert ies. The Ov er loads k eyw or d is one m ore exam ple of a keyw ord t hat sim plifies how y ou can do m or e w it h t he code in y our sam ples. I n essence, it allows y ou t o const ruct a set of pr ocedur es all of which hav e t he sam e nam e but w it h differ ent argum ent t ype specificat ions. When a user invokes a m et hod based on t he set of procedures, t he .NET Fram ew ork aut om at ically det ect s t he specific pr ocedur e t hat m at ches t he input dat a t y pe. You don’t hav e t o use t he Ov erloads k eyword 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.
  11. inherit ance. For sim plicit y, t his sect ion dem onst rat es t he use of t he Ov erloads keyw ord wit hout inv olv ing inherit ance. N ot e You can also achieve overloading wit hout t he Ov erloads key word. Just m ak e sure all t he pr ocedure nam es are ident ical, wit h differ ent value t ype specificat ions for t he argum ent s in each m em ber wit hin t he set of pr ocedures. However, if you use t he Overloads keyword for at least one m em ber in t he 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 t wo inst ances of t he TenPer cent OfI t funct ion procedur e. These inst ances collect iv ely im plem ent t he TenPercent OfI t m et hod for Class3. I f a user ent ers an ar gum 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 inv ok ing t he first funct ion pr ocedur e. This m ight happen if t he user inv okes t he m et hod from a dat abase w it h a colum n of Double values. On t he ot her hand, when t he input for t he TenPercent OfI t funct ion is a st ring, such as 55.5, Class3 aut om at ically inv ok es t he second funct ion procedure. This m ight happen if an applicat ion passes a value dir ect ly from a t ext box t o t he class m et hod. By using t he Over loads k eyw ord in fr ont of bot h versions of t he funct ion, t he dev eloper can leav e it t o t he .NET Fram ework t o figur e out wit h w hich specific funct ion pr ocedur e t o im plem ent t he m et hod. As m or e pot ent ial dat a sources becom e available, it is easy t o add a new copy of t he funct ion pr ocedur e wit h different v alue t ype 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 ent ed in Class3. Aft er hiding t he unnecessary cont r ols on t he form , t he applicat ion 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 et hod in Class3 w it h t he num 1 Double value t ype or a St r ing value t ype based on t he cont ent s of Text Box1. Because t he r et ur n fr om t he m et hod is a Double value, t he argum ent for t he MsgBox funct ions inv ok es t he ToSt r ing m et hod on t he r et urn value. The im port ant point t o not e is t hat ev en t hough t he t w o MsgBox funct ions invoke t he TenPercent OfI t m et hod w it h different v alue t ypes, t hey bot h invok e exact ly t he sam e m et hod wit h exact ly t he sam e synt ax. ‘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.
  12. ’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 obt ain ident ical result s from t he TenPercent OfI t ov erloaded set of funct ions based on t w o differ ent input value t ypes. The form on t he left shows 55.5 in a t ex t box. This t ext box cont ains a St r ing value. The t w o m essage box es on t he r ight show ident ical ret ur n values. How ev er , t heir capt ions confirm t hat 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 Over loads k eyw ord. Som et im es Microsoft can m ake life so sweet ! Figu re 9 - 9 . Ove rloa din g au t om at ica lly m a t ch e s t h e p roce du re in vok e d t o t h e d at a t yp e of t h e ar gu m en t in a st a t e m e n t ca llin g a se t of ove rloa de d p roce du re s. Pr ogr a m m in g Even t s An ev ent is a not ificat ion t hat som et hing happened. As Visual Basic program m ers, you are well awar e of event s from built - in obj ect s, such as form s and but t ons. Many int erm ediat e and advanced program m ers r egular ly creat e cust om classes t hat generat e cust om event s wit h pr ior v ersions of Visual Basic. Adding ev ent s t o cust om classes allows obj ect s based on t he classes t o conv ey inform at ion back t o t he applicat ions t hat inst ant iat e t he obj ect s. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  13. Visual Basic .NET ret ains t he ev ent funct ionalit y fr om earlier v ersions w hile it adds new capabilit ies as well, relat ed t o defining cust om event handlers and wor k ing w it h new sources for ev ent s. This sect ion r ev iews t he basics of ev ent program m ing t o prov ide a st andard background for m or e adv anced t opics, including t he abilit y t o dynam ically define ev ent handlers and new com ponent s t hat can raise ev ent s. Ev e nt Pr ogr a m m in g Con ce pt s Ev en when work ing w it h built - in ev ent s for form s and t heir cont rols, it helps t o hav e a basic underst anding of ev ent program m ing concept s, but a k nowledge of t his t opic is essent ial w hen you dev elop event s for cust om classes. Happily, a few core concept s t hat ar e easy t o grasp can enable you t o declar e and m anage cust om ev ent s. Ev ent s hav e a source or a sender. This source is t he elem ent t hat sends out t he not ificat ion t hat an event happened. A class t hat you cr eat e can be a source. A for m class can be a source. For exam ple, Visual Basic raises t he Load event w hen it opens a form inst ance. Sim ilarly, when a user clicks a but t on on a for m inst ance, t his raises t he Click event for t he but t on. For a source t o raise an ev ent , t wo t hings m ust happen. First , t he ev ent m ust be declared for t he obj ect . You can declare an Ev ent st at em ent . Second, som e code inside t he class for t he obj ect inst ance m ust inv ok e t he RaiseEvent st at em ent . The RaiseEvent st at em ent t riggers an ev ent declared wit h t he Ev ent st at em ent . You can raise an ev ent only from t he class in w hich it occurs. Ther efor e, a but t on cannot raise a Load ev ent for a form on which it r esides. Sim ilarly , a der iv ed class cannot use t he Raise- Ev ent st at em ent t o t rigger an ev ent declar ed in it s base class. Ev ent handlers pr ocess an ev ent . Just because a class inst ance raises an ev ent doesn’t m ean t hat an applicat ion has t o acknowledge t he ev ent . Clicking a but t on befor e y ou add a sub pr ocedur e t o process t he click has no effect . The sub procedur e is an ev ent handler. Ev ent handlers allow applicat ions t o r espond t o ev ent s r aised by class inst ances. Visual Basic can aut om at ically cr eat e em pt y ev ent handlers for t he Windows For m s and t heir cont rols. These em pt y ev ent handlers ar e called st ubs. A st ub includes t he sub procedure declarat ion w it h a nam e for t he procedur e, a list of argum ent s, and a t erm inat ing st at em ent for t he procedur e ( nam ely, End Sub) . St ubs also include a Handles clause t hat associat es t hem w it h a class inst ance and an ev ent nam e. You can det erm ine how your applicat ion r esponds t o an ev ent by placing your own code inside t he sub procedur e. When y ou w rit e ev ent handlers for cust om classes, y ou m ay need t o cr eat e y our own st ub. I f y ou use t he Wit hEv ent s k eyw ord when y ou inst ant iat e an obj ect based on a class, y ou can use t he Visual St udio dev elopm ent envir onm ent t o creat e a st ub for y ou aut om at ically. When using t he Wit hEvent s k eyw or d, you m ust inst ant iat e your obj ect at t he m odule lev el. Wit hout t he Wit hEv ent s keyw ord, ev ent s don’t propagat e from a class t o an obj ect inst ance based on it . Est ablishing an associat ion bet w een an event handler and an ev ent w it h t he Wit hEv ent s k eyw ord requir es you t o specify t he ev ent handler at design t im e. The AddHandler and Rem ov eHandler 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 t im e. You can also use t hese st at em ent s at design t im e. Wit h t hese t w o st at em ent s, y ou don’t have t o inst ant iat e an obj ect using t he Wit hEv ent s keyw ord in order t o process ev ent s raised by t he obj ect . I n t ur n, t his m eans t hat y ou can inst ant iat e w it hin a procedur e or at t he m odule lev el. Recall t hat t he Wit hEv ent s k eyw ord r equires 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 w it h an ev ent handler, y ou m ust wr it e y our own st ub for t he ev ent handler. I will dem onst rat e how t o do t his in a sam ple t hat illust r at es t he use of t he AddHandler st at em ent . Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  14. Usin g Bu ilt - I n For m Ev e n t s Ther e ar e a couple of w ays of m anaging built - in ev ent s wit h Windows Form s and t heir cont r ols fr om t he Windows For m s Designer. Double- clicking a for m ’s capt ion in t he Windows Form s Designer opens t he st ub for t he form ’s default ev ent , t he Load ev ent , in t he Code Edit or. This sam e t echnique works for t he cont r ols on a for m . For ex am ple, double- click ing a but t on on a form opens t he st ub for t he but t on’s default ev ent , a Click ev ent . Aft er adding one or m or e cont r ols on a for m , y ou can select any event for any cont r ol in t he Code Edit or. Choose t he cont r ol nam e from t he Class Nam e dr op- dow n list at t he upper left of t he Code Edit or , and choose t he ev ent nam e fr om t he Met hod Nam e list at t he r ight . Aft er you click an ev ent for t he cont r ol, a st ub for t he ev ent pr ocedur e appears aut om at ically. To display a nondefault event for t he form , select ( Base Class Ev ent s) from t he Class Nam e list and t hen choose a desir ed ev ent 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 t he cont r ols on a form , you will quickly discover an exceedingly large array of ev ent s. Alt hough t he large num ber of ev ent s is useful for fine- grained cont rol ov er t he operat ion of an applicat ion, it m ay be difficult for som e program m ers t o discern t he order of t he ev ent s so t hey can k now which one t o use. The follow ing excerpt fr om t he Code Edit or for Form 4 in t he Ev ent sSam ples solut ion dem onst rat es a st rat er gy for t racking ev ent s. Wit hin each ev ent pr ocedur e is a MsgBox funct ion indicat ing which ev ent generat ed t he cur rent m essage box in an applicat ion. For exam ple, t he m essage box for t he form Load ev ent fir es befor e Form 4 is display ed. When you click t he form ’s Close but t on, y ou w ill not ice t hat t he Closing ev ent fir es pr ior t o t he 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 obj ect for t he Ev ent sSam ples solut ion. N ot e A Windows applicat ion st art s by default wit h For m 1, which is t he obj ect t hat Visual St udio .NET m akes aft er opening a Windows applicat ion for design. By default , t he Windows applicat ion opens t o t his obj ect when you run t he solut ion. However, you can choose anot her obj ect for a Windows applicat ion t o open when it st art s t o r un. Right - click t he solut ion’s nam e in Solut ion Explor er , and choose Propert ies t o open t he Propert y Pages dialog box for t he solut ion. Use t he St art up Obj ect drop- dow n list t o select anot her obj ect . For ex am ple, select ing For m 4 will cause t his form t o open init ially when a user chooses t o run t he solut ion. Ev ent s som et im es fire so quick ly t hat m essage boxes can pile up and m ake discover ing t heir order confusing. I n cases lik e t his, y ou can som et im es set a propert y for an obj ect on t he form — and t hus change it s appearance— t o help indicat e t he order of ev ent s. The procedures for t he MouseEnt er , MouseHov er, and MouseLeav e ev ent s fr om But t on1 dem onst rat e t his appr oach. These ev ent procedur es change t he Back Color pr opert y for But t on1. I nit ially posit ioning t he m ouse over But t on1 changes t he BackColor pr opert y from it s default set t ing t o Syst em .Drawing.Color .Cyan. Because Visual St udio aut om at ically cr eat es a reference t o t he Syst em .Draw ing nam espace w hen it init ializes a Windows applicat ion, y ou can abbreviat e t he set t ing t o Color. Cyan. Leav ing t he m ouse ov er a but t on event ually invok es t he MouseHov er ev ent , which changes t he Back Color set t ing t o Sy st em .Draw ing.Color.Red. Rem ov ing t he m ouse from ov er t he but t on rest or es t he default BackColor set t ing of Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  15. Syst em .Drawing.Syst em Colors.Cont rol. Clicking But t on1 displays a m essage box and shift s t he focus fr om For m 4 t o t he m essage box. This But t on1_Click ev ent is ort hogonal t o t he MouseEnt er and MouseHover ev ent s in t hat click ing t he but t on can int errupt t he t r ansit ion fr om 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 Befor e proceeding t o a second sam ple, it m ay be useful t o r ev iew t he synt ax for an ev ent pr ocedure. Not ice t hat t hey ar e sub pr ocedur es m eant for operat ion in t he cur rent m odule, as specified by t he use of t he Privat e keyw ord. Pr ivat e m arks t he ev ent procedur e for exclusive use in t he cur rent m odule. The argum ent s list can offer you a way of changing t he operat ion of t he ev ent pr ocedur e. The nex t sam ple dem onst rat es t he use of an ev ent argum ent t o cont r ol t he behavior of t he Closing event . Aft er t he argum ent list , t he Handles clause specifies t he obj ect and ev ent t hat t he sub procedur e handles. You cont rol t he operat ion of t he ev ent procedur e by placing cust om code bet ween t he Sub and End Sub st at em ent s. The next select ion of ev ent pr ocedur es shows a pair of procedures for cont rolling how a user can close a form . When a user chooses t o close a form by clicking t he for m ’s Close but t on, t he applicat ion fir es t he Closing ev ent . This event occurs befor e t he form closes. By set t ing t he Cancel ev ent argum ent t o Tr ue in t he Closing event , you can block t he Close ev ent fr om occurr ing ( 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 feat ur e t o perform ot her act ions j ust before closing a for m . For exam ple, y ou can display a m essage blocking t he operat ion of t he form ’s Close but t on and inst ruct ing t he user t o click a but t on t hat launches t he ot her act ions you want done befor e invok ing 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.
  16. m et hod raises t he Closing event , y ou m ust const ruct t he form ’s Closing ev ent procedur e t o opt ionally by pass set t ing t he Cancel argum ent t o Tr ue. The follow ing code excerpt for For m 5 dem onst r at es how t o disable a form ’s Close but t on and redirect t he user t o a but t on on t he for m . The solut ion uses t wo ev ent s. First t he Form 5_Closing event procedure blocks t he Close ev ent from occurr ing by set t ing t he Cancel ev ent argum ent t o bolDisableClose. The m odule- level declarat ion for bolDisableClose set s t he variable’s default value t o Tr ue. The I f…Then…Else st at em ent in t he pr ocedur e displays a m essage box dir ect ing t he user t o click But t on1 t o close t he form . The Click ev ent pr ocedur e for But t on1 set s bolDisableClose t o False befor e inv ok ing t he Close m et hod for t he Me keyw ord t hat r efers back t o t he curr ent form , w hich is Form 5 in t his case. The inv ocat ion of t he Close m et hod, in t ur n, launches t he Form 5_Closing event procedur e, but t his t im e t he pr ocedur e t ak es a different pat h t hr ough it s I f…Then…Else st at em ent because of t he new value for t he 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 oce ssin g Eve n t s Using t h e W it hEv e n t s Ke yw or d The ev ent processing t echniques for t his sam ple and t he next t w o all em anat e from Form 1 in t he Event sSam ple solut ion. Figur e 9- 10 shows t his form t wo different way s. At left is t he form as it looks in t he Windows Form Designer— in design v iew. At r ight is t he form as it appears when y ou r un t he Ev ent sSam ple.ex e file. The differences bet w een t he t wo v iews of t he form ar e t he result of t he Form 1_Load ev ent pr ocedur e. ( See t he follow ing sam ple.) This procedur e adds t ext t o som e cont rols and clears it from ot her cont rols. I n addit ion, it form at s t he alignm ent for t he label and t ext cont r ols as well as resizes t he default Widt h propert y set t ing for t he but t on cont rols. This t ransfor m at ion dem onst rat es a use for t he form Load event t hat m akes it easy t o spot changes t o t he default set t ings for t he cont r ols on a form . I f you need t o duplicat e form set t ings acr oss m ult iple form s or syst em at ically change set t ings across m ult iple for m s, t his k ind of procedure can prove especially conv enient . Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  17. Figu r e 9 - 1 0 . Usin g a form Loa d e ven t pr oce d u r e t o d ocu m e n t you r form a t se t t in gs for a for m ca n h elp in docu m en t ing t h ose se t t in gs an d ap plyin g t h ose se t t in gs in a u n ifor m w a y t o m u lt iple form s in a n a pplica 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.
  18. The for m at right in Figur e 9- 10 per m it s a user t o ent er t wo Byt e value t ype quant it ies in t he Byt e1 and Byt e2 t ext box es. When a user clicks t he Add but t on, t he form r et urns t he t ot 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 t he m ax im um legit im at e Byt e value, t he applicat ion displays a m essage box w it h a r em inder of t he pr oblem . Because t he applicat ion com put es t he sum as a Decim al value t ype, ret ur n values great er t han t he m ax im um don’t generat e a run- t im e er ror. Howev er, you can raise an ev ent t hat ident ifies sum s great er t han 255. I f a user ent ers a value gr eat er t han 255 in eit her t he Byt e1 or Byt e2 t ext box, Visual Basic raises an error because t he Add but t on’s Click ev ent pr ocedur e uses t he CByt e funct ion t o conv ert t he t ext box values t o Byt e dat a t ypes. Befor e rev iew ing 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 eArit hm et ic class. Form 1 relies on t he class t o save t he values in t he t wo input t ext box es, com put e t he sum , and raise t he ev ent . The class list ing includes an ev ent declarat ion, a Privat e st at em ent for declaring t wo int ernal var iables, t wo propert y pr ocedur es, and a funct ion pr ocedur e. The Public accessibilit y qualifier for t he event declar at ion at t he t op of t he list ing m akes t he ev ent available t hr oughout t he Ev ent sSam ple solut ion assem bly. I f By t eArit hm et ic ex ist ed as a st and- alone class proj ect wit h a .dll ext ension, t he Public declarat ion would per m it t he accessibilit y of t he event in ot her pr oj ect s t hat r efer ence t he .dll file. The propert y pr ocedur es nam ed Byt e1 and Byt e2 can accept conv ert ed dat a fr om t ext boxes on Form 1. The class represent s t hese pr opert y set t ings int er nally w it h t he byt 1 and byt 2 var iables, which ar e declared direct ly below t he ev ent declarat ion. A funct ion procedur e, Add2byt e, in Byt eArit hm et ic com put es t he sum and condit ionally raises an er ror. This procedure com put es t he sum of t he t wo t ypes as a Decim al value t ype, w hich it saves in t he m ysum var iable. This design feat ur e av oids t he pot ent ial of a r un- t im e er ror fr om a sum t hat exceeds t he Byt e value lim it . How ev er, Add2byt e also checks for sum s t hat exceed 255. When it finds a sum t hat exceeds t he m ax im um Byt e value, it raises t he TooHigh ev ent and ret ur ns as an event argum ent t he m ysum v ariable value. The Add2byt e procedur e list ing concludes wit h a Ret ur n st at em ent t hat 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.
  19. ’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 et ic class. There ar e t w o especially im port ant feat ur es of t his declarat ion. First , t he declarat ion includes t he Wit hEv ent s k eyw ord. This allows Form 1 t o process ev ent s raised by ba. Second, t he declarat ion occurs at t he m odule lev el. This is m andat ory when y ou use t he Wit hEvent s k eyw ord in t he declarat ion for a class inst ance. I generat ed t he st ub for t he But t on1_Click ev ent procedure by double- clicking t he cont r ol in t he Windows Form s Designer. The ev ent pr ocedur e is generat ed by t he double click on t he cont rol because Click is t he but t on’s default ev ent . Wit hin t he Click event are t wo blocks of code. First t he procedur e conv ert s t he t ex t box ent r ies wit h t he CBy t e funct ion t o Byt e value t y pes from t heir nat iv e St ring value t ypes. Second t he pr ocedur e inv ok es t he Add2byt e m et hod for t he ba class inst ance and st or es t he ret ur n value as a st r ing in Text Box 3. The second procedur e is t he event handler for t he TooHigh event from t he ba class inst ance. I n t he Code Edit or for Form 1, y ou can cr eat e t he st ub for t he ev ent 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 it s r ight . Aft er Visual St udio cr eat ed t he st ub, I had t o add j ust one line of code, which pr esent s a m essage box r em inding t he user t hat 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 r et 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.
  20. As Decimal) Handles ba.TooHigh ’Display event message. MsgBox(“Sum of “ & ReturnValue & “ too large for byte value.”) End Sub Figur e 9- 11 shows t he out com e of t ry ing t o add 4 and 252 w it h t he applicat ion det ailed in t he preceding t wo code segm ent s. Each quant it y alone is a legit im at e Byt e v alue. However, t heir sum exceeds t he m axim um Byt e value. Ther efor e, t he applicat ion displays t he m essage box shown at t he left of Figure 9- 11 befor e populat ing Text Box3 w it h t he r et urn value from t he Byt eAr it hm et ic inst ance. Form 1 appears on t he r ight side of Figur e 9- 11, wit h t he t wo input values and t heir sum . To proper ly close t he solut ion, a user m ust click t he Close App but t on. Figu r e 9 - 1 1 . You can u se a cu st om e ven t t o disp la y a m e ssa ge b ox . Pr oce ssin g Eve n t s w it h t h e AddH a n dle r St a t e m e nt Below t he t hird t ext box in Figur e 9- 11 is t he Open Form 2 but t on. Click ing t his but t on opens a second form t hat dem onst rat es how t o use t he AddHandler st at em ent t o process a raised event . Form 2 has j ust t wo but t ons. That ’s because t his form uses t he t ext boxes on Form 1 t o display input and out put from t he inst ance of Byt eArit hm et ic t hat it declares. Ther efor e, anot her benefit of t his sam ple is t hat it r ev eals how t o pass v alues back and fort h bet ween t w o form s. The only way t hat t he applicat ion will open For m 2 is by a click t o t he Open Form 2 but t on on Form 1. The applicat ion’s logic requir es t hat t her e be num eric ent ries in t he Byt e1 and Byt e2 t ex t box es befor e t he click. Failing t o populat e t he t ext boxes w it h appropr iat e values befor e t he click will generat e a r un- t im e err or . The Click event procedur e for But t on2 on Form 1 follows. Not ice t hat t he But t on2_Click ev ent procedure com m ences by inst ant iat ing an inst ance of Form 2 and referencing it wit h t he fr m Form 2 v ariable. Wit h t he frm Form 2 var iable, t he event procedur e can t hen access elem ent s in t he code behind Form 2. As a subsequent list ing shows, t wo of t hese elem ent s ar e var iables nam ed frm 2byt e1 and frm 2byt e2. The assignm ent st at em ent s in t he Click event procedur e dem onst rat e t he synt ax for copying convert ed t ext box values from one form ( For m 1) t o Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

CÓ THỂ BẠN MUỐN DOWNLOAD

Đồng bộ tài khoản