1. Trang chủ
  2. » Công Nghệ Thông Tin

Wrox’s Visual Basic 2005 Express Edition Starter Kit phần 4 pdf

38 256 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Take Control of Your Program
Trường học Standard University
Chuyên ngành Computer Science
Thể loại Bài viết
Năm xuất bản 2005
Thành phố New York
Định dạng
Số trang 38
Dung lượng 0,92 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Figure 6-1 The new class file will be added to the Solution Explorer window, and you’ll be able to access the codefor it through the context menu or by clicking the View Code button at t

Trang 1

Using classes enables you to segregate information and actions into a self-contained unit This unit canthen be used by anything that has access to it If you keep each class in a separate class module, youcan then import just the ones you want into each project

For example, if you wanted to build another application in the future that used the same Personclass

as the Personal Organizer application, it wouldn’t be as easy to use if the Personclass was defined inthe main form’s file because you would need to include the whole thing It is usually acceptable to keepclasses that work together in one physical file This means you could keep the Personclass and thePersonListclass in the same file if that fits your own style of organization

You can even define classes within classes if that makes sense to your application’s design Internal classes of this type are normally defined as Private so they can be accessed only within the main class’

functionality.

To add a class file to your project, use the Project ➪ Add Class menu command or right-click the project

in the Solution Explorer and choose Add ➪ Class from the submenu Either method will present youwith the Add New Item dialog with the empty class template highlighted (see Figure 6-1) Name theclass something appropriate to the kind of object you are defining and click Add to add it to the project

Figure 6-1

The new class file will be added to the Solution Explorer window, and you’ll be able to access the codefor it through the context menu or by clicking the View Code button at the top of the Solution Explorer.Selecting the class file will also change the context of the Properties window, where you can set a couple

of properties that control how the class is built and the name of the file if you wanted to change it later.When you add a class module, by default it adds an empty class with the same name and defines it as

Public, which means any other part of the application can reference and use the class, as well as any

external program that interfaces with your application The code view of your class will look like this:Public Class MyClassName

End Class

Trang 2

An empty class doesn’t do much; you need to add code to specify its attributes First up are the variablesthat store the information These are usually placed at the top of the class structure and are defined inthe same way as module-level variables are in your form code in a Windows Application project Variables within classes can be defined with a variety of access modifiers, including PrivateandPublic Privatetells Visual Basic Express that the variable is accessible only within this class and willnot be seen outside the class Publicis at the opposite end of the spectrum — a public variable can beaccessed not only by the class and any other part of your application, but also by other programs as well(assuming they can access the class that the variable is part of)

Other access modifiers include Friend, which enables other parts of your program to access the variable(but nothing outside of it can see it), and Protected, which is an extension of Privatethat enablesclasses that inherit behavior from other classes to see their variables

If you put this in action, the class definition would appear similar to the following:

Public Class MyClassName

Private MyString As StringPublic MyInteger As IntegerEnd Class

In this case, the MyStringvariable would be accessible only from within the class, while other parts ofthe application could access and change the contents of MyInteger

Classes often embody this kind of division of information, where some data is for internal use only,while other information is provided to the rest of the program You may be tempted to implement thepublicly available data using Publicvariables, but that allows other code to have access to the data in

a way you may not want to allow

These Publicvariables will be visible in the form of properties on the class, but unlike real properties,the code accessing the class can assign whatever data it wants to the variable, thus potentially corruptingyour class contents Real property definitions enable you to control access to the information

To define a property, you use the Propertystructure, which has the following syntax:

Property propertyName() As StringGet

Return someValueEnd Get

Set(ByVal newValue As String)

Do something with newValueEnd Set

End Property

A property must have a name and a type, which specify how it can be accessed from outside the class.Within the property definition, the code needs to define what is returned if code tries to get the valuefrom the property (the Getclause), and what action should be taken if another part of the programattempts to assign a value to the property (the Setclause)

Trang 3

The sample code can be altered to fit this preferred way of defining a public property, by changing theaccess modifier on MyIntegerto Privateand then returning it and assigning it through a Propertydefinition:

Public Class MyClassNamePrivate MyString As StringPrivate MyIntegerValue As IntegerPublic Property MyInteger() As IntegerGet

Return MyIntegerValueEnd Get

Set(ByVal newValue As Integer)MyIntegerValue = newValueEnd Set

End PropertyEnd Class

Notice in the preceding property definition that it was actually defined with a Publicaccess modifier toexplicitly tell the Visual Basic Express compiler that this property is to be accessible from outside the class.This sample effectively does almost the same thing as giving external code direct access to the privatevariable However, you can write whatever code you require in the Getand Setclauses to control thataccess For example, if the value stored in MyIntegerwere allowed to be within a specified range of 1through 10 only, the Setclause could be modified to ignore values outside that range:

Public Property MyInteger() As IntegerGet

Return MyIntegerValueEnd Get

Set(ByVal newValue As Integer)

If newValue >= 1 And newValue <= 10 ThenMyIntegerValue = newValue

End IfEnd SetEnd Property

The Getclause can be similarly modified if need be In some cases, you may want to allow access toinformation to other areas of your program but not allow it to be modified To disallow write access to aproperty, use the ReadOnlymodifier on the Propertydefinition:

Public ReadOnly Property MyInteger() As IntegerGet

Return MyIntegerValueEnd Get

End Property

Note that the Setclause is not even required (and in fact will cause a compilation error if it does exist)when the property is defined ReadOnly Conversely, some information may be modified via externalcode, but cannot be retrieved This may be for security reasons, or just because it’s not needed In eithercase, use the WriteOnlymodifier in the place of the ReadOnlymodifier and specify the Setclauseinstead of the Getclause

Trang 4

Creating an instance of the custom class and accessing the properties defined within it is done using thesame syntax as accessing the attributes of a control or form:

Dim MySample As New MyClassName

MySample.MyInteger = 6

Methods

If the only thing that the class were capable of was defining, storing, and controlling access to tion through properties, it would be a powerful feature of programming in Visual Basic Express Butthat’s just the beginning, and like the methods on controls such as Buttonsand TextBoxes, a class canhave its own public functions

informa-Methods can be either subroutines or functions, and they have the same syntax as both of these tures (covered in Chapter 5) Because methods are part of the internal structure of the class, they canaccess the private variables defined within the class Therefore, the sample class definition could beextended like so:

struc-Public Class MyClassName

Private MyString As StringPrivate MyIntegerValue As IntegerPublic Property MyInteger() As IntegerGet

Return MyIntegerValueEnd Get

Set(ByVal newValue As Integer)MyIntegerValue = newValueEnd Set

End PropertyPublic Sub MyFunctionName(ByVal ExtraParameter As Integer) MyIntegerValue += ExtraParameter

End SubEnd Class

Class functions and subroutines are accessed by referencing the object name followed by a period (.) andthen the name of the method As you can see, this method of identifying members of objects is usedthroughout Visual Basic Express code, and this consistent approach of accessing information makes iteasy to read programs Using the sample property and method, this access is illustrated as follows:Dim MySample As New MyClassName

Trang 5

The cherry on top of the pie defining a class is the capability to define custom events For any significantoccurrence within the class, you can build a notifying action that other code can receive by writing anevent handler routine

Adding an event to a class is a two-step process First, you need to define the event and identify whatinformation will be included in the message when it occurs Second, you need to tell the class to raise theevent when a particular condition or situation is met

Event definitions are placed outside any other property or method definition and consist of a single-linestatement beginning with the keyword Eventand naming the event followed by its parameter listenclosed in parentheses The syntax is Event EventName(EventParameters)and is demonstratedhere by adding an event named MyEventat the top of the class definition:

Public Class MyClassNameEvent MyEvent(ByVal MyBigInteger As Integer)

Private MyString As StringPrivate MyIntegerValue As IntegerPublic Property MyInteger() As IntegerGet

Return MyIntegerValueEnd Get

Set(ByVal newValue As Integer)MyIntegerValue = newValueEnd Set

End PropertyPublic Sub MyFunctionName(ByVal ExtraParameter As Integer) MyIntegerValue += ExtraParameter

End SubEnd Class

Once the event has been defined, it then needs to be raised at an appropriate time Events can bedesigned and raised for all sorts of reasons Your class may need to raise an event if an error occurs, or itmight need to inform the application every time a particular function is performed You may also need

to raise an event every time a particular interval of time has passed

Telling Visual Basic Express that the event should be fired is done through the RaiseEventcommandand has the syntax RaiseEvent EventName(EventParameters) The subroutine in the sample classcould thus be modified like this:

Public Sub MyFunctionName(ByVal ExtraParameter As Integer) MyIntegerValue += ExtraParameter

If MyIntegerValue > 10 ThenRaiseEvent MyEvent(MyIntegerValue)End If

End Sub

Trang 6

The final class definition containing private variables, public properties and methods, and event tion appears as follows:

defini-Public Class MyClassName

Event MyEvent(ByVal MyBigInteger As Integer)

Private MyString As StringPrivate MyIntegerValue As IntegerPublic Property MyInteger() As IntegerGet

Return MyIntegerValueEnd Get

Set(ByVal newValue As Integer)MyIntegerValue = newValueEnd Set

End PropertyPublic Sub MyFunctionName(ByVal ExtraParameter As Integer) MyIntegerValue += ExtraParameter

If MyIntegerValue > 10 ThenRaiseEvent MyEvent(MyIntegerValue)End If

End SubEnd Class

You saw how the event handler routine side of things is implemented in Chapter 5, but to follow theexample all the way through, here is a sample routine that handles the event that is defined and raised

in the previous example:

Private WithEvents MySample As MyClassName

Private Function SomeFunction() As Boolean

MySample = New MyClassNameMySample.MyInteger = 6MySample.MyFunctionName(3)MySample.MyFunctionName(3)End Function

Private Sub MyEventHandler(ByVal BigNumber As Integer) Handles MySample.MyEventMessageBox.Show(“Number getting big: “ & BigNumber)

End Sub

This code creates an instance of the MyClassNameclass and assigns an initial value of 6 to the MyIntegerproperty It then performs the MyFunctionNamemethod twice, each time effectively incrementing theMyIntegerproperty by 3, with a result of 9 and then 12

When the subroutine calculates the value of 12, it raises the event MyEvent, which is being handled bythe MyEventHandlerroutine, and a message dialog is displayed warning the user that the number isgetting big

You may have noticed the extra keyword required as part of the definition of the class —WithEvents For more information on how WithEventsworks, see Chapter 9.

Trang 7

Special Method Actions

As you were typing out code in Chapter 5 and taking notice of the cool IntelliSense features of VisualBasic Express, you may have noticed that some methods appeared to have multiple ways of being

called, or multiple signatures This is known as method overloading and is a relatively new addition to the

Visual Basic language

Method overloading enables you to define several functions with the same name but with different sets

of parameters Each function can do completely different things, although it’s typical for functions of thesame name to perform the same kind of action but in a different context For example, you might havetwo methods that add an interval to a date variable, where one adds a number of days, while the otheradds a number of days and months These could be defined as follows:

Public Sub AddToDate(ByVal NumberOfDays As Double)MyDate.AddDays(NumberOfDays)

End Sub

The With-End With Block

Sometimes you will want to work with a particular object or control extensively

Rather than type its name each time, you can use a special shortcut Visual BasicExpress provides — the With-End Withblock

The Withstatement identifies a particular variable name to be treated as a shortcut tothe compiler Wherever a property or method is preceded by a single period (.), thecompiler will automatically insert the variable identified in the Withstatement Forexample, the function definition in the previous example could be replaced with thisWithblock:

With MySample.MyInteger = 6.MyFunctionName(3).MyFunctionName(3)End With

You can have only one shortcut variable at any one time, although you can embedWithblocks inside other Withblocks This is particularly useful with very complexobjects where you initially work with properties at one level but then need to deal withattributes further down the hierarchy:

With MyOtherSample.MyString = “Hello”

With MyOtherObject.MyStringTwo = “World”

End WithEnd With

You’ll find further examples of using Withblocks throughout this book as a way ofsaving space It can make your code more readable, so I encourage you to use Withinyour own applications

Trang 8

Public Sub AddToDate(ByVal NumberOfDays As Double, _ByVal NumberOfMonths As Integer)

MyDate.AddDays(NumberOfDays)MyDate.AddMonths(NumberOfMonths)End Sub

You can also define a couple of special methods in your class that will automatically be called when the

objects are first created and when they are being destroyed Called constructors and destructors, these

methods can be used to initialize variables when the class is being instantiated and to close systemresources and files when the object is being terminated

Disposeand Finalizeare the two methods called during the destruction of the object, but the methodcalled when a class is created is important enough to be discussed now The Newmethod is called when-ever an object is instantiated The standard Newmethod syntax accepts no parameters and exists bydefault in a class until an explicitly defined Newmethod is created; that is, the following two class defini-tions function in the same way:

Public Class MyClass1

End Class

Public Class MyClass2

Public Sub New()End Sub

Public Class MyClass2

Private MyInteger As IntegerPublic Sub New(ByVal MyIntegerValue As Integer)MyInteger = MyIntegerValue

End SubEnd Class

Dim MyObject As New MyClass2(3)

Bringing the capability of method overloading into the equation, however, enables you to define multipleversions of the Newmethod in your class The following definition would enable you to define objects andinstantiate them without any parameter or with a single integer value:

Public Class MyClass2

Private MyInteger As IntegerPublic Sub New()

MyInteger = 0End Sub

Public Sub New(ByVal MyIntegerValue As Integer)MyInteger = MyIntegerValue

End Sub

Trang 9

One last important point: If your class is based on another class, to create the underlying class you mustcall the special method MyBase.Newas the first thing in your Newmethod definition so that everything

is instantiated correctly

The following Try It Out brings all of this information about how to create a class together by creating thePersonclass for the Personal Organizer application, complete with multiple Newmethods to demonstrateoverloading

1. Start Visual Basic Express and create a new Windows Application project Add a new class ule to the project by selecting Project ➪ Add Class Name the class Person.vband click Add toadd it to the project

mod-2. In the class definition, start by defining private variables to store the Personinformation:Private mFirstName As String

Private mLastName As StringPrivate mHomePhone As StringPrivate mCellPhone As StringPrivate mAddress As StringPrivate mBirthDate As DatePrivate mEmailAddress As StringPrivate mFavorites As StringPrivate mGiftCategories As IntegerPrivate mNotes As String

3. For each of these variables, create a full property block with Getand Setclauses For now, simplytranslate the property to the private variable For example:

Public Property FirstName() As StringGet

Return mFirstNameEnd Get

Set(ByVal value As String)mFirstName = valueEnd Set

End Property

4. Revise the code for setting the birth date so that it does not allow dates in the future You can dothis by comparing the date value passed in against the special date keyword Now, which returnsthe current date and time:

Public Property BirthDate() As DateGet

Return mBirthDateEnd Get

Set(ByVal value As Date)

If value < Now ThenmBirthDate = valueEnd If

End SetEnd Property

Trang 10

5. Create a read-only property called DisplayNamethat concatenates the first names and last names:Public ReadOnly Property DisplayName() As String

GetReturn mFirstName + “ “ + mLastNameEnd Get

7. Return to Form1.vbin Design view and add a button to the form Double-click the button to ate and edit the Clickevent handler and add the code to create a Personobject and populate it:Private Sub Button1_Click(ByVal sender As System.Object, _

cre-ByVal e As System.EventArgs) Handles Button1.ClickDim pPerson As Person = New Person(“Brett”, “Stott”)With pPerson

8. Run the application and click the button After a moment you should be presented with a sage dialog with the text Brett Stott You’ve created your first class, complete with over-loaded methods and read-only properties

mes-Control Freaks Are Cool

In a moment, you’re going to take a look at how to interact with controls by changing their propertiesand intercepting their methods, so it’s worth reviewing what can be done at design time to initialize theattributes of your controls even before you begin to run

The Properties window (see Figure 6-2) enables you to customize the appearance of each element on theform, including the form itself It also can be used to control behavior through attributes related to dataand other nonvisible aspects of the control

Trang 11

Figure 6-2

Design-time Properties

Rather than set the properties through simple text fields, the variety of methods to set the attributes is richwith drop-down lists, visual cues, and a hierarchy that groups related properties together In Figure 6-2,the Appearance group for a Buttoncontrol is shown Out of all the properties in the visible area, onlyBorderSizeand Sizeare simple text edits

The remainder of the properties use a number of different editor types For example, BackColorandBorderColordrop down three lists of colors to choose from and provide a sample of the color optionright in the Properties window The lists include system colors, which give you the capability to set yourcontrols’ color schemes to match the rest of the Windows system — if users change their system settings,your application can stay in synch with the rest of the environment (see Figure 6-3)

Figure 6-3

Trang 12

The Fontproperty is actually an object and can be expanded as shown in Figure 6-3 to show the ual fields, such as Name and Size While these properties can be set individually, the Fontproperty can

individ-be used to show a general Font dialog window that enables you to set several of these attributes at once

In addition, the Font Nameproperty offers a visual preview of the font option selected right in theProperties window so you can verify it’s the correct choice

The Properties window can be organized to show the properties in either alphabetical order or in gories, which is the default view To switch between the two, click the Categorized and Alphabetic but-tons at the top of the pane

cate-An interesting addition with Visual Basic Express is the capability to access the events that the selectedcontrol has Click the Events button, which is a little yellow lightning strike icon, and the properties will

be replaced by a list of events Any event that has an event handler routine explicitly intercepting it willhave the name of the routine listed here, and you can easily change the routines handling the differentevents by clicking the drop-down arrow and choosing them from the list You’re safe in that only thesubroutines that have the correct signature will be listed

If you’re not sure what a particular property or event does, the Properties window will give you a briefdescription at the bottom of the pane This tray area also serves another purpose for complex objectssuch as data-bound controls and visual components such as menus and toolbars

Setting the Tab Order

Speaking of navigating through a form by pressing the Tab key raises a valuable point By default, asyou add controls to the design surface of a form or user control, they have a TabIndexvalue automati-cally assigned to them This TabIndexcontrols the order in which the components are traversed whenthe user presses Tab

In most applications, you’ll find that this order is, well, orderly and logical, usually flowing from left toright and top to bottom, much like you would read this page If you add your controls in an order thatdiffers from this, or if you realize when running the application that it doesn’t quite make sense for thenavigation flow to work the way you’ve set it up, you’ll need to change the TabIndexproperty

These values can be set directly in the Properties window like any other property, or you can use the TabOrder Wizard, which makes setting them easy To change to Tab Order mode, use the View ➪ Tab Ordercommand

Tab Order view will place the current TabIndexproperties over each control on the form (see Figure 6-4)

To change the order, select each control in the order you want the navigation to occur by clicking them Aseach control is selected, its TabIndexnumber will be set to the next available number (starting with 0),and the TabIndexmarker will change color to indicate it has been set

Once every element has been set, the TabIndexmarkers will reset to the original gray color to indicateyou have done them all At this point you can start again, or exit Tab Order mode through the View menu You may notice that this tab order is also followed at design time This enables you to verify that the taborder is what you intended, and it gives you a logical way of proceeding through your controls as youedit their properties and events

Trang 13

Figure 6-4

Editing Collections of Objects

If an object such as a MenuStripis selected in Design view, among the properties you’ll find objects thatcontain a collection of subordinate items In the case of MenuStrip, the Itemsproperty identifies anarray of MenuItemsthat belong to the control Each MenuItemis a control in its own right and can beaccessed by clicking it in the form’s Design view, but a more natural way of editing the properties of thecollection is through a Collection Editor

It may appear that there are several of these Collection Editors, each specifically targeted at a particulartype of object In reality, there is one Collection Editor that Visual Basic Express customizes dynamically

to suit the control you are editing

The Collection Editor for the Itemscollection of a MenuStripis shown in Figure 6-5 Each of the objectsbelonging to the MenuStrip’s Itemscollection is shown in the left-hand list, while the right-hand prop-erties view provides direct access to its properties

The beauty of this Collection Editor paradigm is that it is recursive In Figure 6-5, the Edit menu item isselected and the properties list has been scrolled down to the DropDownItemsproperty This is anothercollection object that in turn can be edited through the Collection Editor (and if an item in that collectionhad a collection of sub-items, they could also be edited through this process, and so on)

Items within a collection can be repositioned or removed using the command buttons situated betweenthe two lists The Collection Editor is smart enough to know which types of items are valid for inclusion

in the current list type In the case of a MenuStrip, four kinds of items can be added to the collection —

a standard menu item, a ComboBox, a TextBox, and a separator To add the required item, choose itstype from the drop-down list and click Add

In the following Try It Out, you’ll modify the menu and toolbar of the Personal Organizer application

so that it contains only the items that you’ll need This will demonstrate the advanced aspects of theProperties window, including the Collections Editor and in-place property editing

Trang 14

Figure 6-5

1. Start Visual Basic Express and open the Personal Organizer solution you worked with inChapter 5 If you don’t have this project handy, you can find a copy of it in the Chapter06\PersonalOrganizer Startfolder of the downloaded code that you can get from the Wroxwebsite (at www.wrox.com), complete with MenuStripand ToolStripwith standard items

2. Some of the items that were added through the Insert Standard Items command are sary, and some commands you’re going to need later Therefore, you need to customize themenus and toolbars First, change the toolbar so that it contains only what you need

unneces-3. The ToolStriphas seven default items — New, Open, Save, Print, Cut, Copy, and Paste — withtwo separator lines dividing the buttons into logical groups It also has a gripper so that it can

be dragged around Because it doesn’t apply in this application with only the one ToolStrip,turn the gripper off by changing the GripStyleproperty to Hidden

You can use all of these buttons except for Open, so go ahead and right-click the picture of theopen folder and choose Delete to remove it from the ToolStrip Do the same for the Help but-ton as you won’t implement help in this application

4. Two useful commands that you’ll build the code for later in this book are not present They areshortcuts to delete the currently selected person from the list and to enable the user to log off.Click on the ToolStripto make it active and show the in-place editor In the Type Here area,enter Deleteand press Enter to save the new button

Repeat this action and add a new button with a text label of Logoff

Trang 15

5. The buttons look a bit bulky at the moment and out of place because they are text buttons (theothers are icons) Select Deleteand then bring up the Smart Tag dialog window by clickingthe small arrow on the right.

Change the DisplayStyleto Imageand click on the ellipsis button next to the Imageproperty

to import a new image In the Select Resource dialog, click the Import button to select an imagefile on your computer If you don’t have one handy, browse to the Chapter 06\Imagesfolderincluded in the downloaded code for this book and select delete.gif

When you’ve found the image you want to use, click Open to return to the Select Resource dialog,make sure it looks right in the Preview pane, and click OK

6. Repeat the process in step 5 with the Logoff button The image used in the example shown inFigure 6-6 can be found in the same folder of the downloaded code and is named user.gif

Figure 6-6

7. It would be nice to have the Delete command grouped with the New, Save, and Print buttons,

so click and drag the icon to where you want it to be positioned and release it You can range the items on any toolstrip or menu like this

rear-8. Now it’s the MenuStrip’s turn Rather than use the in-place editor, this time you’ll use theCollection Editor for the Itemsproperty Select the MenuStripand locate Itemsin thePropertieswindow Click the ellipsis button to bring up the Collection Editor

9. Select the File menu’s object — it has a name of fileToolStripMenuItem— and find itsDropDownItemscollection and again click the ellipsis button to dive down an extra level in theCollection Editor

10. You won’t need the Open or Save As commands, so select each one in the list and click theDelete button to remove them The menu looks a bit awkward with a separator between Newand Save now that they’re by themselves, so remove that separator as well

11. Select ToolStripMenuItemfrom the item drop-down and click Add By default, it will beadded to the bottom of the list, so click the Move Up button to move the new item above theExit command Change the new item’s properties as follows:

Trang 16

Name—logoffToolStripMenuItem

Text—&Logoff

Image— The same image you used for the Logoff button in step 6

When you’re finished, the list of items should look like Figure 6-7 To save all these changes,click OK to return to the main MenuStrip’s Item Collection Editor

Figure 6-7

12. Leave all the menu items in place for the Edit menu, but add a new separator and an extramenu item at the bottom of the list AToolStripSeparatoritem will draw a line in betweenother commands to group them for your users The extra ToolStripMenuItemshould havethe following properties set:

Name—deletePersonToolStripMenuItem

Text—&Delete Person

Image— The same image you used for the Delete button in step 5

13. Save the Edit menu by clicking OK, and then edit the Tools menu by selecting toolsToolStripMenuItemin the list and clicking the ellipsis button next to its DropDownItemsproperty.Remove all of the items that are currently there by selecting each one and clicking the Deletebutton In their place, add two new menu items for Export Data and Import Data Their settings,respectively, are as follows:

Trang 17

14. Add a new View menu item with a name of viewToolStripMenuItem Just like when youadded the Logoff button to the Edit menu, adding the View menu will result in its being added

to the end of the menu list, so move it “up” one position so it will appear before the Help menu

15. In the View menu’s DropDownItemscollection, add two ToolStripMenuItemsto give userseasy access to the Person List and the Web Browser (this will be added in Chapter 9) Set theproperties as follows:

When you’re done, click OK in the main MenuStrip’s Collection Editor to save all of the changes made.Run the application and compare it to Figure 6-8

Figure 6-8

Custom Controls — Empower Yourself

When you create a user control, you’re just defining a specialized class that includes visual components.That means all the information outlined in this chapter also applies to custom-built controls, includingthe creation of properties and methods, and the definition and invocation of events

In Chapter 4, you created two basic user controls, which you then dynamically added to the main formarea when the user clicks the appropriate button However, you didn’t add any properties, methods, orevents to the user control’s definition, so you may assume that you cannot access any information withinthe control

Trang 18

That’s actually not the case If you take a look at the drop-down list that Visual Basic Express providesthrough IntelliSense for the controls, you’ll find a list of properties and methods that are exposed by theuser control itself, along with Friendscope variables for each of the components you added to the control.Because they are defined with a scope of Friend, these controls can be accessed from the form that ownsthe user control, but using these properties is similar to creating public variables within a class — itallows the external code full access to the component — possibly more access than you would want.

On top of this, any events that are fired by the individual components within a user control are notpassed on to the owner of the user control The only events that the owner can access — assuming thecontrol has been defined WithEventsso that the events can be intercepted — are those belonging tothe user control itself

Because of both of these reasons, it’s best to explicitly define the members of the user control and in sodoing regain control of what can and cannot be done to the internal elements of the control Visual BasicExpress keeps the code underneath the user control clean by keeping the objects and properties that youadd to the design surface in a separate module

By default, this module is hidden from view in the Solution Explorer, but you can access it by clickingthe Show All Files button at the top of the Solution Explorer pane The module will be named the same

as the form or control with an extra extension of Designer, so the code behind a control named

MyControlwould be contained in a file named MyControl.Designer.vb

What you’ll find in this module is that Visual Basic Express uses the same class constructs you need touse when creating your own classes Each control is defined using the WithEventskeyword so theirevents can be trapped, and there is a Newmethod defined that initializes the properties of each compo-nent with the values you’ve set in Design view

The result of this separation of visual design code and the underlying program logic is that when youmodify the user control’s code, you start with an empty class:

Public Class MyUserControl

End Class

All your own events, methods, and properties are defined within this class in exactly the same way asany other class you might create However, because this class is connected to the hidden designer class,you have access to the components and their members Each component will be accessible in the Classdrop-down list at the top of the code editor, too, so you can easily find the events that you can interceptfor each control

To illustrate how you might define your own members for a user control, the following Try It Out walksthrough adding properties and methods to the PersonalDetailscustom control that is part of thePersonal Organizer application

1. Return to the Personal Organizer project that you’ve been working on in this chapter Add anew class module by selecting Project ➪ Add Class and name it Person.vb Follow the steps in

Trang 19

2. Open the code view for PersonalDetails.vbby right-clicking its entry in the SolutionExplorer and choosing View Code Add a private module-level variable to store the Personclass associated with the control and add a public property to allow other parts of your applica-tion to access it:

Private mPerson As Person

Public Property Person() As PersonGet

Return mPersonEnd Get

Set(ByVal value As Person)mPerson = valueEnd Set

End Property

3. Add code to the Setclause to automatically update the component controls on the user controlwhenever the Personproperty is updated:

Private mPerson As Person

Public Property Person() As PersonGet

Return mPersonEnd Get

Set(ByVal value As Person)mPerson = value

txtFirstName.Text = mPerson.FirstNametxtLastName.Text = mPerson.LastNametxtHomePhone.Text = mPerson.HomePhonetxtCellPhone.Text = mPerson.CellPhonetxtAddress.Text = mPerson.AddresstxtEmailAddress.Text = mPerson.EmailAddresstxtFavorites.Text = mPerson.FavoritestxtNotes.Text = mPerson.Notes

dtpBirthdate.Value = mPerson.BirthDate

End SetEnd Property

4. When the user clicks the Newbutton on the menu or toolbar or the Add Person button, it would

be handy for the form to tell the control to revert to its default values in case it is currently beingdisplayed Add a subroutine called ResetFields, resetting all the controls and the Personobject to empty values:

Public Sub ResetFields()txtFirstName.Text = vbNullStringtxtLastName.Text = vbNullStringtxtHomePhone.Text = vbNullStringtxtCellPhone.Text = vbNullStringtxtAddress.Text = vbNullStringtxtEmailAddress.Text = vbNullStringtxtFavorites.Text = vbNullStringtxtNotes.Text = vbNullString

Ngày đăng: 14/08/2014, 01:20