Top Banner
Contents Lesson 1: Animation..................................... 2 Lesson 2: MDI Forms..................................... 6 Lesson 3: Creating database applications...............11 Lesson 4: Navigating the database application..........15 Lesson 5: Database ADO Control.........................17 Lesson 6: Using the Data Environment...................23 Lesson 7: Using Internet Controls......................32 Lesson 8:Building an ActiveX Control in VB.............35 Lesson 9: Data Repeater Control........................41 Lesson 10: Error Handling..............................47 Err Object....................................50 Lesson 11: Entry Validation............................53 Input Validation..............................55 Lesson 12: More tools for enhancing your project.......59 Masked Edit Control...........................59 Chart Control.................................61 Drag and Drop.................................63
80
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: VB Advanced Exercises

Contents

Lesson 1: Animation....................................................................................................2

Lesson 2: MDI Forms..................................................................................................6

Lesson 3: Creating database applications................................................................11

Lesson 4: Navigating the database application.......................................................15

Lesson 5: Database ADO Control.............................................................................17

Lesson 6: Using the Data Environment....................................................................23

Lesson 7: Using Internet Controls............................................................................32

Lesson 8:Building an ActiveX Control in VB..........................................................35

Lesson 9: Data Repeater Control..............................................................................41

Lesson 10: Error Handling........................................................................................47

Err Object..............................................................................................50

Lesson 11: Entry Validation......................................................................................53

Input Validation....................................................................................55

Lesson 12: More tools for enhancing your project.................................................59

Masked Edit Control.............................................................................59

Chart Control........................................................................................61

Drag and Drop.......................................................................................63

Exercises have been adapted from examples found on these sites:

http://www.vbtutor.net/vbtutor.html

http://pages.cpsc.ucalgary.ca/~saul/hci_topics/

http://people.revoledu.com/kardi/index.html

http://www.kidwaresoftware.com/vbproj.htm

Page 2: VB Advanced Exercises

Lesson 1: Animation In this lesson, you will be able to create animation showing a butterfly flapping its wings. The following example uses eight picture of a butterfly which display a butterfly flapping its wing at different stages.

1 The pictures are stored on the VLE so copy the above images to the folder where you will save your program.

2 Set the properties for the first image as shown below:

Data Control Property Value

Image1 Picture bfly1.gif

Top 2000

Left 1500

Visible True

3 Insert 7 more images onto the form. Image1 will have properties as shown above. All other images will have their visible property set to false.

Data Control Property Value

Image2 Picture bfly2.gif

Top 2000

Left 1500

Visible False

Repeat this for all other images.

4 Add a command button. The form should look the one below.

Data Control Property Value

2

Page 3: VB Advanced Exercises

Command button Name cmdAnimate

Caption Animate

5 Add the following code to the command button to make the next image visible with each click of the button

Private Sub cmdAnimate_Click()If Image1.Visible = True Then

Image1.Visible = False Image2.Visible = True

ElseIf Image2.Visible = True ThenImage2.Visible = FalseImage3.Visible = True

ElseIf Image3.Visible = True ThenImage3.Visible = FalseImage4.Visible = True

ElseIf Image4.Visible = True ThenImage4.Visible = FalseImage5.Visible = True

ElseIf Image5.Visible = True ThenImage5.Visible = FalseImage6.Visible = True

ElseIf Image6.Visible = True ThenImage6.Visible = FalseImage7.Visible = True

ElseIf Image7.Visible = True ThenImage7.Visible = FalseImage8.Visible = True

ElseIf Image8.Visible = True ThenImage8.Visible = FalseImage1.Visible = True

End IfEnd Sub

6 Run the program to see the butterfly flapping its wings.

3

Page 4: VB Advanced Exercises

7 If you wish to create the effect of the butterfly flapping its wings and flying at the same time, then you could use the Left and Top properties of the object. Below is an example of how to also change the top property to give the effect of the butterfly flapping its wings and moving up at the same time.

Add the emboldened code to the click event.

Private Sub cmdAnimate_Click()If Image1.Visible = True Then

Image1.Visible = FalseImage2.Visible = TrueImage2.Top = Image2.Top – 100

ElseIf Image2.Visible = True ThenImage2.Visible = FalseImage3.Visible = TrueImage3.Top = Image3.Top – 100

ElseIf Image3.Visible = True ThenImage3.Visible = FalseImage4.Visible = TrueImage4.Top = Image4.Top – 100

ElseIf Image4.Visible = True ThenImage4.Visible = FalseImage5.Visible = TrueImage5.Top = Image5.Top – 100

ElseIf Image5.Visible = True ThenImage5.Visible = FalseImage6.Visible = TrueImage6.Top = Image6.Top – 100

ElseIf Image6.Visible = True ThenImage6.Visible = FalseImage7.Visible = TrueImage7.Top = Image7.Top – 100

ElseIf Image7.Visible = True ThenImage7.Visible = FalseImage8.Visible = TrueImage8.Top = Image8.Top – 100

ElseIf Image8.Visible = True ThenImage8.Visible = FalseImage1.Visible = TrueImage1.Top = Image1.Top – 100

End IfEnd Sub 

 8 Run the program to see the animation.

 Exercise

4

Page 5: VB Advanced Exercises

Add another line of code to each if statement to make the butterfly move to the right.

Animation using a Timer

1 Use the above program, and add a timer to the form.

Data Control Property Value

Timer Enabled False

Interval 100

2 Move the code from the cmdAnimate_Click event to the Timer1_Timer() event.

3 Add the following code to the cmdAnimate_Click event:

Private Sub cmdAnimate_Click() If Timer1.Enabled = True Then Timer1.Enabled = False Else Timer1.Enabled = True End IfEnd Sub

This code will turn the timer on and off with each click of the button.

Exercise

Create another animation using the set of images T1 .. T10 which you will find on the VLE.

5

Page 6: VB Advanced Exercises

Lesson 2: MDI FormsThe forms that you have been using so far are single forms. In Visual Basic you can use Multiple Document Interface (MDI) Forms, a form that can contain multiple forms. You can only have one MDI form in a project

Here is how to create MDI Form:

1. Start Visual Basic Standard Exe project. 2. In the Project Window, right Click, and choose Add > MDI Form

from the pop-up window.

3. Go to Form1. Change the MDI Child Property of Form1 (and all other forms if exist) into True. This will make Form1 a child form instead of a parent

4. In the VB menu, select Project > Project1 Properties. In the General Tab, StartUp Object, select MDI Form1, then OK. This is to make VB run for the first time by calling the MDI Form.

6

Page 7: VB Advanced Exercises

Adding a Menu1. In the Project Window, double click the MDI Form1 to put the MDI

Form in front. 2. In the Menu of VB, click Tools > Menu Editor or you can use Ctrl-E.

The menu Editor will appear.3. In the Caption, type &File then in the name, type mnuFile then

click the Next button.4. In the Caption, type &Exit then in the name, type mnuExit then

click the right arrow button. In the Shortcut list, choose Ctrl-X, then the Next button.

7

Page 8: VB Advanced Exercises

5. In the Caption, type &Window then in the name, type mnuWindow then click the Next button.

6. In the Caption, type &Calendar then in the name, type mnuCalendar then click the right arrow button. In the Shortcut list, choose Ctrl-L, then the Next button

7. Press OK 8. Now you have a menu in the MDI Form, click File>Exit and enter

9. In the mnuExit_Click procedure, type

Private Sub mnuExit_Click() End

End Sub

10. Run the program, and look at the Window menu and try the Exit menu.

Add a calendar1. Add a new Components to the toolbox by right clicking on the

toolbox and selecting Components. 2. Find Microsoft Calendar Control. Check the checkbox and press

OK 3. See that the Calendar control is added to your toolbox 4. Add a new form to the project.5. Change the Name property of the new form into frmCalendar.

Change the Caption property into Calendar. 6. Add a Calendar Control from the Toolbox into frmCalendar.

Change the MDIChild property to true.

8

Page 9: VB Advanced Exercises

7. Add the following code:

Private Sub Form_Load() Me.Width = 4800 Me.Height = 3600End Sub

Private Sub Form_Resize() Calendar1.Width = frmCalendar.Width - 500 Calendar1.Height = frmCalendar.Height - 500End Sub

8. Add a command button onto frmCalendar. Change the Name property to cmdToday, the Caption property to Today and resize it small enough to put in the right corner of the calendar. Type the following code into the click event of the command button:

Private Sub cmdToday_Click()Calendar1.Today ‘this is an in-built method

End Sub 9. Now in the MDI Form, you select the menu Window > Calendar

and select, then type the code below:

Private Sub mnuCalendar_Click()If mnuCalendar.Checked = True Then

'it is checked, so make it uncheckedfrmCalendar.HidemnuCalendar.Checked = False

Else ' now it is unchecked, so make it checked frmCalendar.ShowmnuCalendar.Checked = True

End IfEnd Sub

10 Add code below to call the Calendar Form from the MDI form as the first form and to maximize the MDI form:

Private Sub MDIForm_Load() frmCalendar.ShowmnuCalendar.Checked = TrueMDIForm1.WindowState = vbMaximized

End Sub

11 Run the program. Select the menu Window > Calendar several times to see the effect of the Checked menu.

9

Page 10: VB Advanced Exercises

Exercise

Add another form to the project and make it another MDIChild. Add another option to the window menu to also be able to open this new form.

10

Page 11: VB Advanced Exercises

Lesson 3: Creating database applicationsVisual basic allows us to manage databases created with different database programs such as MS Access. In this lesson we will see how we can access database files in the VB environment.

In the following example, you will create a simple database application which enables you to browse customers' names.  To create this application:

1 Insert the data control into the new form. Place the data control somewhere at the bottom of the form. Name the data control as dtaNavigator.

Data Control Property Value

dtaNavigator Name dtaNavigator

Caption Click to Browse Customers

DatabaseName NWIND.MDB

RecordSource Customers

To be able to use the data control, we need to connect it to a database. You can use the database files that come with VB6. Select NWIND.MDB as the database file.  To connect the data control to this database, double-click the DatabaseName property in the properties window and select the above file, i.e NWIND.MDB.  Next, double-click on the RecordSource property to select the customers table from the database. You can also change the caption of the data control to "Click to browse Customers".

2 After that, we will place a label and change its caption to Customer Name.

Data Control Property Value

Label1 Caption Customer Name3 Insert another label and name it as lblCustName

Data Control Property Value

11

Page 12: VB Advanced Exercises

Label2 Name lblCustName

Caption Leave blank

DataSource dtaNavigator

DataField ContactName

Fontsize 14

Leave the label empty as the customers' names will appear here when we click the arrows on the data control. We need to bind this label to the data control for the application to work. To do this, open the label's DataSource and select dtaNavigator that will appear automatically. One more thing that we need to do is to bind the label to the correct field so that data in this field will appear on this label. To do this, open the DataField property and select ContactName.

4 Now, press F5 and run the program. You should be able to browse all the customers' names by clicking the arrows on the data control.

 The Design  Interface.

12

Page 13: VB Advanced Exercises

The Runtime Interface

13

Page 14: VB Advanced Exercises

Exercise

Add other fields using exactly the same method. For example, you can add address, City and telephone number to the database browser.

14

Page 15: VB Advanced Exercises

Lesson 4: Navigating the database applicationYou have learned how to create a simple database application using a data control. In this lesson, you will work on the same application but use some slightly more advanced commands. The data control supports some methods that are useful in manipulating the database, for example, to move the pointer to a certain location. The following are some of the commands that you can use to move the pointer around.

dtaNavigator.RecordSet.MoveFirst              ' Move to the first recorddtaNavigator.RecordSet.MoveLast               ' Move to the last recorddtaNavigator.RecordSet.MoveNext             ' Move to the next recorddtaNavigator.RecordSet.Previous               ' Move to the first record

*note: dtaNavigator is the name of the data control

1 Add 4 command buttons and set the properties as shown:

Data Control Property Value

Command1 Name cmdMoveFirst

Caption First Record

Command2 Name cmdMoveNext

Caption Next Record

Command3 Name cmdMovePrevious

Caption Previous Record

Command4 Name cmdMoveLast

Caption Last Record

dtaNavigator Visible False

These buttons will be used to navigator around the database without using the data control. You still need to retain the same data control (as in the last lesson) but set the property Visible to False so that users will not see the data control and will use the buttons to browse through the database instead.

2 Add the following code:

15

Page 16: VB Advanced Exercises

Private Sub cmdMoveFirst_Click() dtaNavigator.Recordset.MoveFirstEnd Sub

Private Sub cmdMoveLast_Click() dtaNavigator.Recordset.MoveLastEnd Sub

Private Sub cmdMoveNext_Click() dtaNavigator.Recordset.MoveNextEnd Sub

Private Sub cmdMovePrevious_Click() dtaNavigator.Recordset.MovePreviousEnd Sub

3 Run the application to try out the navigation buttons: 

 

16

Page 17: VB Advanced Exercises

Lesson 5: Database ADO ControlIn the previous lessons you built a VB database applications using a data control. However, the data control is not a very flexible tool as it could work only with limited kinds of data and must work strictly in the Visual Basic environment. To overcome these limitations, we can use a much more powerful data control in VB known as the ADO control. ADO stands for ActiveX data objects. As ADO is ActiveX-based, it could work in different platforms (different computer systems) and different programming languages. Besides, it could access many different kinds of data such as data displayed in the Internet browsers, email text and even graphics other than the usual relational and non-relational database information.

To be able to use the ADO data control, you need to insert it into the toolbox. Select Microsoft ActiveX Data Control 6 from Components.

The following example will illustrate how to build a relatively powerful database application using the ADO data control.

Data Control Property Value

Form1 Name frmBookTitle

Caption Book Titles – ADO Application

Adodc1 Name adoBooks

Caption Book

1. First of all, name the new  form as frmBookTitle and change its caption to Book Tiles- ADO Application.  Secondly, insert the ADO data control and name it as adoBooks and change its caption to book.

2. To be able to access and manage a database, you need to connect the ADO data control to a database file. We are going to use BIBLIO.MDB that comes with VB6. To connect ADO to this database file, follow the steps below:

a) Click on the ADO control on the form and open up the properties window.

17

Page 18: VB Advanced Exercises

b) Click on the ConnectionString property, the following dialog box will appear.

When the dialog box appears, select the Use Connection String Option. Next, click build and at the Data Link dialog box, double-Click the option labelled Microsoft Jet 4 OLE DB provider.

 c After that, click the Next button to select the file BIBLO.MDB. You can click on Test Connection to ensure there is a proper connection of the database file. Click OK to finish the connection.

d Finally, click on the RecordSource property and set the command type to adCmd Table and Table name to Titles. Click OK.

18

Page 19: VB Advanced Exercises

3. Next, insert the necessary labels, text boxes and command buttons. The runtime interface of this program is shown in the diagram below, it allows adding and deletion as well as updating and browsing of data.

 The properties of all the controls are listed below:

Data Control Property Value

Form1 Name frmBookBitle

19

Page 20: VB Advanced Exercises

Caption Book Titles – ADO Application

Adodc1 Name adoBooks

Caption Book

Label1 Name lblApp

Caption Book Titles

FontSize 16

Label2 Name lblTitle

Caption Title:

Label3 Name lblYear

Caption Year Published:

Label4 Name lblISBN

Caption ISBN

Label5 Name lblPubID

Caption Publisher’s ID

Label6 Name lblSubject

Caption Subject

20

Page 21: VB Advanced Exercises

TextBox1 Name txtTitle

DataSource adoBooks

DataField Title

TextBox2 Name txtPub

DataSource adoBooks

DataField Year Published

TextBox 3 Name txtISBN

DataSource adoBooks

DataField ISBN

TextBox4 Name txtPubID

DataSource adoBooks

DataField PubID

TextBox5 Name txtSubject

DataSource adoBooks

DataField Subject

Command1 Name cmdSave

Caption &Save

Command2 Name cmdAdd

Caption &Add

Command3 Name cmdDelete

Caption &Delete

Command4 Name cmdCancel

Caption &Cancel

21

Page 22: VB Advanced Exercises

Command5 Name cmdPrev

Caption <

Command5 Name cmdNext

Caption >

Command6 Name cmdExit

Caption E&xit

Now, you need to write code for all the command buttons. After which, you can make the ADO control invisible.

For the Save button, the program codes are as follow:

Private Sub cmdSave_Click()adoBooks.Recordset.Fields("Title") = txtTitle.TextadoBooks.Recordset.Fields("Year Published") = txtPub.TextadoBooks.Recordset.Fields("ISBN") = txtISBN.TextadoBooks.Recordset.Fields("PubID") = txtPubID.TextadoBooks.Recordset.Fields("Subject") = txtSubject.TextadoBooks.Recordset.Update

End Sub

22

Page 23: VB Advanced Exercises

For the Add button, the program codes are as follow:

Private Sub cmdAdd_Click()adoBooks.Recordset.AddNew

End Sub

For the Delete button, the program codes are as follow:

Private Sub cmdDelete_Click()Confirm = MsgBox("Are you sure you want to delete this record?", vbYesNo, "Deletion Confirmation")If Confirm = vbYes Then

adoBooks.Recordset.DeleteMsgBox "Record Deleted!", , "Message"

ElseMsgBox "Record Not Deleted!", , "Message"

End IfEnd Sub

For the Cancel button, the program codes are as follow:

Private Sub cmdCancel_Click()txtTitle.Text = ""txtPub.Text = ""txtPubID.Text = ""txtISBN.Text = ""txtSubject.Text = ""

End Sub

For the Previous (<) button, the program codes are

Private Sub cmdPrev_Click()If Not adoBooks.Recordset.BOF Then

adoBooks.Recordset.MovePreviousIf adoBooks.Recordset.BOF Then

adoBooks.Recordset.MoveNextEnd If

End IfEnd Sub

23

Page 24: VB Advanced Exercises

For the Next(>) button, the program codes are

Private Sub cmdNext_Click()If Not adoBooks.Recordset.EOF Then

adoBooks.Recordset.MoveNextIf adoBooks.Recordset.EOF Then

adoBooks.Recordset.MovePreviousEnd If

End IfEnd Sub

ExerciseCreate another form that will allow you to view publishers details using the ADO control. Add text boxes and link to the ADO control so you can see the field that you want to add.

24

Page 25: VB Advanced Exercises

Lesson 6: Using the Data Environment

This time we are using the recommended database access mechanism for linking to an Access Databases from VB.

This is the interface that will be created. The table is shown in a grid at the top of the form, and two frames are used for adding and removing records.

Firstly, you need to create a small database.1. Open up MS Access and create a database called CD

Collection.mdb.2. Create a table called CDs.3. Add the following fields and make ArtistName and

AlbumTitle a composite primary key.

25

Page 26: VB Advanced Exercises

4. Add a couple of entries to the database

Next you need to create a new project in VB1. Start up VB with a Standard EXE project. 2. Save that project to the same folder that your Database was saved

in. 3. Go to the Project menu and select Components. In the Designers

tab, select the checkbox for Data Environment and click OK.

the references - designers window

4. This will add an item to your project menu. Go to the new menu item and select it from Project - Add Data Environment.

5. The following window will pop up, and in it you should right-click on Connection1 and select the Properties item from the list:

26

Page 27: VB Advanced Exercises

the DataEnvironment edit window

6. The first thing we need to do is set up the connection to the database (which is what Connection1 will be to the rest of the application). When the properties window comes up,

a) Select Microsoft Jet 4.0 OLE DB Provider as the data you want to connect to and click Next

b) Browse for your Database file, select it, and then remove the path (so in the picture below, the highlighted text will get deleted)

c) You can test the connection to the database by pressing the Test Connection button, but it should work fine.

the Data Link properties dialog box

7. Once that's set, just click OK.

27

Page 28: VB Advanced Exercises

8. Next, right-click on Connection1 in the Data Environment window like you did above and pick Add Command. You'll see a thing called Command1 pop up hierarchically underneath Connection1.

9. Right-click on Command1 and select Properties from the menu that pops up and do the following to customize Command1:

a) Change Command Name to DataTable b) Select the SQL Statement radio button c) In the textbox underneath that radio button, enter the

query: select * from CDs order by ArtistName, AlbumTitle

d) In the Advanced tab, change the Lock Type (it's a combo-box) from 1-Read Only to 3-Optimistic so that you can write to the database.

e) Press Apply, then OK.

the command properties window

10. Right click and hold the button on DataTable in the Data Environment window, and drag it to your main form.

11. When you release the right button on your form, you'll get a popup menu, from which you should select Data Grid

12. You will get a data grid on your form that will be perfectly connected to your database. Push the play button to see it running.

28

Page 29: VB Advanced Exercises

right-click-drag from DataTable to the form to drop a pre-bound data display!!

Now you need to complete the interface to allow data to be added and removed from the database.

1 Add two frames to the form and add the controls as shown below.

Data Control Property Value

Frame Name fraAddEntry

Caption Add Entry

Frame Name fraRemoveEntry

Caption Remove Entry

2 Add the following controls to the Add Entry frame.

Data Control Property Value

Label Caption Artist Name

Text box Name txtArtistName

Label Caption Album Title

Text box Name txtAlbumTitle

29

Page 30: VB Advanced Exercises

Label Caption Number of Tracks

Text box Name txtTrackCount

Command button Name cmdAddEntry

Caption Add this info

3 Add the following controls to the Remove Entry frame:

Data Control Property Value

Label Caption Select the entry you want to remove and click the button.

Command button Name cmdRemoveEntry

Caption Remove Selected

30

Page 31: VB Advanced Exercises

4 Add the following code to size the form and disable the command button:

Option Explicit' couple of global vars for size trackingDim MinHeight As LongDim MinWidth As Long

Private Sub Form_Load() ' record the height and size of the window for reference MinHeight = Form1.Height MinWidth = Form1.Width

' disable the add button cmdAddEntry.Enabled = FalseEnd Sub

5 We will use the Form_Resize() method. This gets called whenever you resize the form, and we will just use it to make a resized form look attractive.

Private Sub Form_Resize() ' check to see if the form is getting too small If MinHeight > Form1.Height Then Form1.Height = MinHeight Exit Sub ElseIf MinWidth > Form1.Width Then Form1.Width = MinWidth Exit Sub End If

' resize the flexgrid to fit nicely on the screen DataGrid1.Width = Form1.ScaleWidth DataGrid1.Height = Form1.ScaleHeight / 2

' resize the columns to look attractive ‘(40% for each text column, 20% for Track)

DataGrid1.Columns(0).Width = 0.4 * DataGrid1.Width DataGrid1.Columns(1).Width = DataGrid1.Columns(0).Width DataGrid1.Columns(2).Width = DataGrid1.Width -

(DataGrid1.Columns(0).Width * 2) - 60

' reposition and resize the frames on the screen to fit nicely ‘need to do this by trial and error

fraAddEntry.Top = (Form1.ScaleHeight / 2) + 100 fraAddEntry.Height = (Form1.ScaleHeight / 2) - 150 fraAddEntry.Width = (Form1.ScaleWidth * 0.64) fraRemoveEntry.Height = (Form1.ScaleHeight / 2) - 150 fraRemoveEntry.Top = (Form1.ScaleHeight / 2) + 100

31

Page 32: VB Advanced Exercises

fraRemoveEntry.Width = (Form1.ScaleWidth * 0.36) - 100 fraRemoveEntry.Left = fraAddEntry.Width + 100

End Sub

6 Add the code to add a new record to the database in cmdAddEntry_Click()

Private Sub cmdAddEntry_Click() ' add a new entry to our table. With DataEnvironment1.rsDataTable .AddNew !ArtistName = txtArtistName !AlbumTitle = txtAlbumTitle !Tracks = txtTrackCount .Update End With

' requery the db and re-bind the data source to the data grid DataEnvironment1.rsDataTable.Requery Set DataGrid1.DataSource = DataEnvironment1 Call Form_Resize ' clear the text fields once the new record is added txtArtistName = "" txtAlbumTitle = "" txtTrackCount = "" ' set the focus back to the artist name textbox txtArtistName.SetFocusEnd Sub

8 Now you need the remove code in the cmdRemoveEntry_Click() subroutine.

Private Sub cmdRemoveEntry_Click() ' remove the currently selected item from the database DataEnvironment1.rsDataTable.Delete adAffectCurrentEnd Sub

9 Now you need to go to the form design window, you have three textboxes: txtArtistName, txtAlbumTitle, and txtTrackCount. Double click on each of them in turn to get their associated Change methods and fill in the following code:

Private Sub txtArtistName_Change() ' check to see if each text field has contents. If they all have ' contents (ie, they're not empty) enable the "Add Entry" button.

32

Page 33: VB Advanced Exercises

If txtArtistName.Text <> "" And txtAlbumTitle.Text <> "" _And txtTrackCount.Text <> "" Then

cmdAddEntry.Enabled = True Else

cmdAddEntry.Enabled = False End If

End Sub

Private Sub txtAlbumTitle_Change() ' call the artist name change method as the code here would be ' exactly the same. Call txtArtistName_ChangeEnd Sub

Private Sub txtTrackCount_Change() ' call the artist name change method as the code here would be ' exactly the same. Call txtArtistName_ChangeEnd Sub

10 Next add some validation to make sure the entry for the Track is numeric.

Private Sub txtTrackCount_KeyPress(KeyAscii As Integer) ' TrackKey will store which key was pressed as an _ascii_ value. Dim TrackKey As String TrackKey = Chr(KeyAscii) ' if the key pressed was a)not a number and b)not the backspace key, ' just erase the keystroke (it won't get processed or sent) If (Not IsNumeric(TrackKey) And Not (KeyAscii = vbKeyBack)) Then KeyAscii = 0 End IfEnd Sub

11 Make sure you have saved your project in the same folder as you saved your Database.

33

Page 34: VB Advanced Exercises

Lesson 7: Using Internet ControlsThis exercise will show you how to use the Microsoft Internet Control to create a help menu.

1 Open a new project. To use the WebBrowser tool select Project/Components. In the Components dialog box click the check box for Microsoft Internet Controls. Click OK and you will have the WebBrowser in the toolbox.

2 Place 4 buttons and a WebBrowser onto the form as shown.

3 Name the buttons as shown below in the code:

Data Control Property Value

Command 1 Name cmdClose

Caption Close

Command 2 Name cmdPrevious

Caption Previous

Command 3 Name cmdNext

Caption Next

Command 4 Name cmdMenu

Caption Menu4 Create these 3 html files and save them into the same folder

where you are saving the project.

mainHelp.htm

34

WebBrowser1

<html><head>

<title>Help File</title></head>

<body><h1 align=center>HELP MENU</h1>

<h3 align = center><a href="help1.htm">Help on Finding Records</a><br><br>

<a href="help2.htm">Help on Adding New Records</a><br></h3></body>

Page 35: VB Advanced Exercises

Help1.htm

Help2.htm

5 Code the buttons:

Private Sub cmdClose_Click() EndEnd Sub

Private Sub cmdHome_Click() WebBrowser1.Navigate ("file://c:/Joanne/html/mainHelp.htm")End Sub

Private Sub cmdNext_Click()

35

<html><head>

<title>Finding Records</title></head>

<body><h1 align=center> Finding Records</h1><br><br><h4>If you want to find a record all you need to do is: ....</body></html>

<html><head>

<title>Adding Records</title></head>

<body><h1 align=center> Adding Records</h1><br><br><h4>If you want to add a new record ....</body></html>

Add the path for your htm files. This is just an example.

Page 36: VB Advanced Exercises

WebBrowser1.GoForwardEnd Sub

Private Sub cmdPrevious_Click() WebBrowser1.GoBackEnd Sub

7 Code the form to size it.

Private Sub Form_Load() WindowState = 0 Form1.Top = ScaleHeight * 0.3 Form1.Left = ScaleWidth * 0.3End Sub

Private Sub Form_Resize() WebBrowser1.Left = 0 WebBrowser1.Width = ScaleWidth WebBrowser1.Height = 0.9 * ScaleHeight WebBrowser1.Navigate ("file://c:/Joanne/html/mainHelp.htm")End Sub

8 Save and run the program.

36

Add the path for your htm files. This is just an example.

Page 37: VB Advanced Exercises

Lesson 8:Building an ActiveX Control in VBThis set of instructions will show you how to build, test and package a trivial ActiveX control. The control has no code attached to it: it simply displays some text saying 'Hello World'.

1. Building an ActiveX Control Project Start VB From the File Menu, select New Project Select ActiveX Control from the dialog box.

2. Naming your Control Project From the Project Menu, select Project1 Properties In the dialog box, change the Project Name and Project description as

shown below. This will determine how your 'friendly' name of your component is displayed later on, as well as the name of your compiled .ocx.

37

Page 38: VB Advanced Exercises

3. Naming your actual control  In the project explorer window, select UserControl1. Then change the

Name Property from UserControl1 to  HelloWord1. Your window should look like the one below.

Original Renamed

4. Building your control Drop a label into the Control Using the Label properties, change its caption to "Hello World" and its font

to 14 point

38

Page 39: VB Advanced Exercises

Create a 16x15 bitmap (using Microsoft paint) that has some kind of descriptive image (you can just compose it by writing the letters HW). From the HelloWorld UserControl properties, point the ToolboxBitmap to that bitmap. It will eventually appear in the Toolbox on the left (rather than the generic toolbox control image, shown greyed out on the bottom of the left pane below).

5. Saving your control This is probably a good time to save the project, just in case! Save it in a

folder called (say) HelloWorldV1

6.  Testing your control by two methods Now we will test this simple control via two methods. The first method uses Internet Explorer. If you click the play button, VB will

start Internet Explorer, and you will see your control in it. The second method for testing a control uses VB directly. From the File

menu, select Add Project and then select the Standard EXE icon (the dialog box is the same as the one already seen in Step 1)

From the Project explorer, right-click on Project1(Project1) to raise the context menu, and select 'Set as Startup'. From now on, when you press the play button it will start this program instead of using Internet explorer.

Close the form containing your hello world control. and then raise the Project1 Form.

39

Page 40: VB Advanced Exercises

You will see an icon in the bottom of the toolbar: its tooltip will say HelloWorld1. Select this, and drop it into the form. Your window should look something like the one below.

Feel free to browse the properties of your HelloWorld control in the Properties window: you will see that its properties is not a label! Rather, these are the default properties that every ActiveX control made in VB have.

Just for fun, add a few more HelloWorld controls into your form window. The nice thing about controls is that you can have lots of them!

7.  Testing the project  Test the program by hitting play. It should bring up the following window.

40

Page 41: VB Advanced Exercises

8.  Saving the project and the project group Save the project group (this is both the control and the sample application

you just made). To do this cleanly, when you save create a new folder called "Test" under "HelloWorldV1" and save everything to that.

9. Compiling your OCX  Through the project explorer, close Project1 and open up your HelloWorld

control again. Compile your control by selecting 'Make HCIHelloWorld1.ocx' from the file

menu. Save it in your HelloWorldV1 folder. Close down VB

10. Testing your OCX from a new VB project. Start a new version of VB, and create a new .exe project. Select Components from the Project menu, as shown below. Scroll the list

until you find HCI Hello World Version 1. Check the checkbox, and then Ok. This will add the hello world control icon to your controls window.

41

Page 42: VB Advanced Exercises

Lesson 9: Data Repeater Control

The data repeater control allows you to display more than one database record at a time, without using a grid type control. You decide how you want to display each record by building your own Visual Basic control! The data repeater then hosts this new control (displayed in the Visual Basic toolbox like all other controls), displaying several instances in a Visual Basic application. To load this control, select Components from the Projects menu, and then select Microsoft DataRepeater Control.

To use the data repeater control requires a bit of work, but it is worth it. There are four steps: (1) build the ActiveX control to display the database record, (2) expose properties in the ActiveX control, (3) compile the ActiveX control and (4) bind the ActiveX control to the data repeater control. Rather than discuss these steps in general, we will build an example using the Publishers table from the books database. This is, by far, the best way to illustrate how this powerful control is used.

In this example, we will use the data repeater control to display multiple publisher names and phone numbers (a ‘computer Rolodex’). This information will come from the Publishers table of the BIBLIO.MDB database. This example will follow the four steps just outlined: (1) build the ActiveX control that displays the record, (2) expose the ActiveX control properties, (3) compile the ActiveX control, and (4) bind the ActiveX control to the data repeater control.

Build an ActiveX Control

Building an ActiveX control is not any harder than building a Visual Basic application. We build the control, compile it, and register it in the Windows registry. The control we build here will contain two pieces of information from the Publishers table of BIBLIO.MDB – the Company Name field and the Telephone field.

1 Start a new Visual Basic project. In the New Project window, select ActiveX Control. Select the Project menu item and choose Project Properties. In this window, assign a Project Name of vbdbPublisher. This name will be used as a prefix for the compiled control.

2 Place two label controls and two text boxes on the user control form. Assign these properties:

UserControl1: Name ctlPublisher

Label1: Caption Publisher

42

Page 43: VB Advanced Exercises

Text1: Name txtPublisher

Label2: Caption Phone Number

Text1: Name txtPhone

3 Resize the control form so it just fits the space. My form looks like this:

4 Save the control (ctlPublisher.ctl) and project (vbdbPublisher.vbp) to make sure you don’t lose anything.

Expose ActiveX Control Properties

We need to add code to our ActiveX control to make the text box controls Text properties available for database binding within the data repeater control. We need to make it possible to both read and set these properties.

1 Open the form code window. Under Tools menu, select Add Procedure. Set Type to Property, Scope to Public, Name to PublisherName. Repeat these steps to create a Property named PublisherPhone.

2 The previous steps created the code structures that allow us to read (Property Get statements) and set (Property Let statements) property values. The code for these structures is:

Public Property Get PublisherName() As String

PublisherName = txtPublisher.Text

End Property

Public Property Let PublisherName(ByVal vNewValue As String)

txtPublisher.Text = vNewValue

43

Page 44: VB Advanced Exercises

End Property

Public Property Get PublisherPhone() As String

PublisherPhone = txtPhone.Text

End Property

Public Property Let PublisherPhone(ByVal vNewValue As String)

txtPhone.Text = vNewValue

End Property

This code just makes sure proper values are available. One thing to note: by default, all arguments and returned values are defined to be Variant. Make sure, in this example, you change all these default types to String (our property types).

3 We also need to let the data repeater control know when any of the Text properties change. Add this code to the two text box Change events:

Private Sub txtPhone_Change()

PropertyChanged "PublisherPhone"

End Sub

Private Sub txtPublisher_Change()

PropertyChanged "PublisherName"

End Sub

Under the Tools menu, choose Procedure Attributes. Click on Advanced button. For both properties, under Data Binding check Property Is data bound and Show in data bindings collection at design time.

4 Resave the application.

44

Page 45: VB Advanced Exercises

Compile the ActiveX Control

We’re now ready to compile and register the control so it becomes available for the data repeater (and any other Visual Basic project you may build). Choose the File menu option and click Make vbdbPublisher.ocx. Click OK. If you there are no errors in your code, the control will be compile and an OCX file saved in the directory you specify. Your control is now ready to use with the data repeater.

45

Page 46: VB Advanced Exercises

Bind the ActiveX Control to the Data Repeater Control

1 Start a new Standard EXE application (a Visual Basic project).

2 Add a DataEnvironment and to it add Command1 which should be linked to the Publisher table.

3 Add the data repeater control to your toolbox, then add it to your form. Set these properties:

DataRepeater1: Caption Publisher Phone Numbers

DataSource DataEnvironment1

DataMember Command1

RepeatedControlName vbdbPublisher.ctlPublisher

To set the RepeatedControlName property, click the drop-down arrow that appears. You will be shown a list of all qualifying controls. Select the one we just created (vbdbPublisher.ctlPublisher). When you do this, the form is populated with the control. My form looks like this (you may have to do some resizing to get things to fit nicely):

4 We need to bind the properties of our ActiveX control to fields in the database table connected to the data control (which is connected to the data repeater). Right-click the data repeater control and choose Properties. Select the RepeaterBindings tab. In the PropertyName combo box, choose PublisherName. In the DataField combo box, choose Name. Click Add to add the binding to the list box.

46

Page 47: VB Advanced Exercises

Repeat these steps to bind the PublisherPhone property to the Telephone data field. Click OK when done.

5 Save the application. Run it and you should see:

You now have a scrollable list of Publisher phone numbers. This is a great tool for displaying multiple records without using the grid tools.

47

Page 48: VB Advanced Exercises

Lesson 10: Error Handling

To demonstrate the importance of error handling in the exercises that follow you will create a program that divides two numbers first without capability for error handling.

After checking the result of your first program, then you will modify your program for error handling.

1 Start a new project and create the form as follows:

‘Divide by Zero programOption Explicit

Private Sub lblResult_Click()Dim numerator As DoubleDim denominator As Double

numerator = Val(txtInput(0).Text)denominator = Val(txtInput(1).Text)

lblResult.Caption = "Result is " & numerator / denominatorEnd Sub

Private Sub txtInput_GotFocus(Index As Integer)lblResult.Caption = "Click Here to Perform Division"txtInput(Index).Text = ""

End Sub

48

Control array called: txtInput

lblResult

Page 49: VB Advanced Exercises

Test your program using the following test data:

Numerator Denominator Result9 23 -64 0

The result from the last pair of values is a run time error.

You need to modify the divide-by-zero program to include an error handling routine.

The program will need to include an error handling routine that will give an error message to the user but will not crash..

'Divide by zero error handling programOption Explicit

Private Sub lblResult_Click() Dim numerator As Double Dim denominator As Double On Error GoTo divideByZeroHandler 'enables the error trap numerator = Val(txtInput(0).Text) denominator = Val(txtInput(1).Text) lblResult.Caption = "Result is " & numerator / denominator Exit Sub ‘prevents error handler being executed - if no error divideByZeroHandler: 'label for error handling lblResult.Caption = "Error - it is illegal to divide by zero"End Sub

On error GoTo divideByZeroHandler is an error trap. If any errors in the program occur then control is moved to the label dividebyZeroHandler.

49

Add the emboldened lines to your program

Page 50: VB Advanced Exercises

If the division by zero does not occur Exit sub is the next statement to be executed. Exit sub is used to divide the procedure code from the error handling code. Without the Exit sub, the error handling code is executed – even if an error is not raised.

divideByZeroHandler: is the label for the error handling code. Note that it ends with a colon “:”The code in the handler should only be executed if an error occurs.

Nested On Error Statement

Note that the above program assumes the user inputs number values into the two text boxes. However, if the user enters text values, a run time error will be created. The error created will be a mismatch error (i.e. errors that occur when the program tries to store a non-digit characters into a numeric variable).

On Error statements can be nested to direct an error to a specific error handler.

Update the divide-by-zero program to include an input error handler:

Private Sub lblResult_Click() Dim numerator As Double Dim denominator As Double On Error GoTo inputHandler numerator = txtInput(0).Text denominator = txtInput(1).Text On Error GoTo divideByZeroHandler lblResult.Caption = "Result is " & numerator / denominator Exit Sub divideByZeroHandler: 'label for error handling lblResult.Caption = "Error - it is illegal to divide by zero" Exit Sub inputHandler: lblResult.Caption = "Attempted non-numberic input"end sub

50

Page 51: VB Advanced Exercises

Err Object

The Err object provides information about the raised error in six properties and provides two methods. Using the Err object allows the programmer to provide detailed error information. The Err object stores information about the raised error.

Properties/Method Data Type DescriptionDescription (properties)

String A string describing the error

Number (properties) Long Internal error number determined by Visual Basic or a component with which the program interacts (such as a control)

Source (properties) String File name where the error was raised or the source of the error, if the error was outside the application.

Clear (Methods) Clear an errorRaise (Methods) Raises an error

The following program randomly raises an error and handles the error.

Create the form as shown:

Type the following code:

51

cmdPrint

Page 52: VB Advanced Exercises

'Using the Err objectOption Explicit

Private Sub cmdPrint_Click() Dim num As Integer Call Cls 'clears the form Font.Size = 12 'set form Font size to 12 pt On Error GoTo errorHandler 'set trap 'randomly create an error Randomize Select Case Int(Rnd() * 3) Case 0 num = 999999999 'overflow error Case 1 num = 88 / 0 'divide by zero error Case 2 num = "an error" 'type mismatch error End Select Exit Sub 'exit procedure errorHandler: Print "Source: " & Err.Source Print "Error: " Select Case Err.Number Case 6 'overflow ForeColor = vbRed Case 11 'divide by zero ForeColor = vbGreen Case 13 ' type mismatch ForeColor = vbBlue Case Else Print "unexpected error" End Select Print Err.Description ForeColor = vbBlackEnd Sub

52

Page 53: VB Advanced Exercises

Pressing Print clears the form and sets the form’s Font property size to 12 pt. On Error GoTo errorHandler sets the error trap. The Select case that starts on line 12 randomly raises an error.The statement

Print "Source: " & Err.SourceDisplays the Err objects Source property. A Select case tests the number contained in the Err objects Number property for an Overflow error, Divide-by-zero error, or the type mismatch error. Once the error type is identified, the forms Forecolor property is changed. The err object’s Description property is then printed.

Page 54: VB Advanced Exercises

Lesson 11: Entry Validation

Throughout your work with databases, you will find that viewing database information is an easy task with Visual Basic. Things quickly become difficult, though, when you want to modify information in a database. And, things become very difficult when you allow your user to type information. That’s why, if at all possible, don’t allow your user to type things. Use point and click type controls whenever possible.

Checking input information from a user requires programming on your part. You must ensure that information being put in a database is correct. There are two steps to checking information from a user: entry validation and input validation. Entry validation is associated with text box controls and checks for proper keystrokes. Input validation is associated with several control types and checks to make sure entries and choices meet certain requirements. In this section, we address entry validation. Input validation is addressed in the next section of this chapter.

Entry validation checks for proper keystrokes. For example, if a numerical entry is needed, only allow the pressing of number keys. If spaces are not allowed, don’t allow them. If an input must be in upper case letters, don’t allow lower case letters to be typed. Restricting keystrokes is referred to as key trapping.

Key trapping is done in the KeyPress event procedure of a text box. Such a procedure has the form (for a text box named txtText):

Sub txtText_KeyPress (KeyAscii as Integer)...

End Sub

In this procedure, every time a key is pressed in the corresponding text box, the ASCII code for the pressed key is passed to the procedure as the argument KeyAscii. With key trapping, if KeyAscii is an acceptable value, we do nothing. If KeyAscii is not acceptable, we set KeyAscii equal to zero and exit the procedure. Doing this has the same result of not pressing a key at all. ASCII values for all keys are available via the on-line help in Visual Basic. The BASIC function Asc can also be used to determine a key’s ASCII code. And some keys are also defined by symbolic constants. Where possible, we will use symbolic constants; else, we will use the ASCII values.

54

Page 55: VB Advanced Exercises

As an example, say we have a text box (named txtExample) and we only want to be able to enter upper case letters (ASCII codes 65 through 90, or, correspondingly, symbolic constants vbKeyA through vbKeyZ). The KeyPress procedure would look like (the Beep causes an audible tone if an incorrect key is pressed):

Sub txtExample_KeyPress(KeyAscii as Integer)If KeyAscii >= vbKeyA And KeyAscii <= vbKeyZ Then Exit SubElse KeyAscii = 0

Beep

End IfEnd Sub

In key trapping, it's advisable to always allow the backspace key (ASCII code 8; symbolic constant vbKeyBack) to pass through the KeyPress event. Else, you will not be able to edit the text box properly. Modifying the above example, this code would be:

Sub txtExample_KeyPress(KeyAscii as Integer)If (KeyAscii >= vbKeyA And KeyAscii <= vbKeyZ) Or KeyAscii = vbKeyBack Then Exit SubElse KeyAscii = 0 BeepEnd IfEnd Sub

Rather than just beep when an unacceptable keystroke is encountered, you can also use key trapping to automatically correct invalid inputs. For example, if the input requires all upper case letters, you can use the BASIC UCase function to convert any lower case letters to upper case letters.

55

Page 56: VB Advanced Exercises

Exercise:1 Place a text box onto the form and name it txtYearBorn.2 Code the txtYearBorn_KeyPress event as follows:

Private Sub txtYearBorn_KeyPress(KeyAscii As Integer)If (KeyAscii >= Asc("0") And KeyAscii <= Asc("9")) Or KeyAscii = vbKeyBack Then Exit SubElse Beep KeyAscii = 0

End If

End Sub

3 Click the Year Born text box. Try some typing. You should only be able to type numbers (or use the backspace key) in the Year Born entry box.

Input Validation

In the example just studied, although the user can only input numeric data for the Year Born field, there is no guarantee the final input would be acceptable. What if the input year is past the current year? What if the year is 1492? A second step in validation is to check values in context. Do the input values make sense? Do the values meet established rules? This step is input validation.

Some common validation rules are:

Is this field required? If a field is required and no input is provided, this could cause problems.

Is the input within an established range? For example, if entering a day number for the month of April, is the value between 1 and 30?

Is the input the proper length? Social security numbers (including hyphens) require 11 characters. If 11 characters are not detected, the input is not a valid social security number. The BASIC Len function can be used here, as can a text box MaxLength property (to limit the length).

Is the input conditional? Some fields only need to filled in if other fields are filled in. For example, if a user clicks to ship to another address, you need to make sure that address exists.

Is the input a primary key? If so, and the user has the capability of entering a value, we must insure it is a unique value. Each primary key value in a table must be different.

56

Page 57: VB Advanced Exercises

The amount of input validation required is dependent on the particular field. Many times, there is none needed. You, as the programmer, need to examine each input field and answer the questions posed above: is the field required, must it be within a range, is it length restricted, is it conditional? Any Yes answers require code to do the validation.

For our example we have been creating, we will write a general procedure named ValidateData that is called in the Click event of the Save button. The user clicks this button when done editing, making it a great place to check validity. If any validation rules are violated, we don’t allow the requested change(s).

Field validation insures the integrity of the information we are putting in a database. We always need to maintain that integrity.

As mentioned above , the Year Born must be validated. We will make sure that the year has no more than four characters, is not greater than the current year and is greater than 150 years prior to the current year (by not hard coding a minimum year, the code automatically upgrades itself). We will also make sure the user enters an Author Name.

1. Add a procedure named ValidateData with a Boolean argument AllOK (if True, all validation rules were met). Add this code:

Private Sub ValidateData(AllOK As Boolean)Dim Message As StringDim InputYear As Integer, CurrentYear As IntegerAllOK = TrueMessage = ""'Check for nameIf Len(txtAuthor.Text) = 0 Then Message = "You must enter an Author Name." + vbCrLf txtAuthor.SetFocus AllOK = FalseEnd If'Check length and range on Year BornInputYear = Val(txtYearBorn.Text)

57

Page 58: VB Advanced Exercises

CurrentYear = Val(Format(Now, "yyyy"))If Len(txtYearBorn.Text) <> 0 Then If InputYear > CurrentYear Or InputYear < CurrentYear - 150 Then

Message = Message + "Year Born must be between" & _ Str(CurrentYear - 150) & " and" & Str(CurrentYear)

txtYearBorn.SetFocus AllOK = False End IfElse Message = "You must enter a year born" AllOK = FalseEnd IfIf Not (AllOK) Then MsgBox Message, vbOKOnly + vbInformation, "Validation Error"End IfEnd Sub

In this code, we first check to see if an Author Name is entered and then validate the Year Born field. If either validation rule is violated, the variable AllOK is set to False and a message box displayed.

2. Set MaxLength property for txtYearBorn text box to 4.

3. Modify the cmdSave_Click event to read (new lines are italicized)::

Private Sub cmdSave_Click()Dim Valid As BooleanCall ValidateData(Valid)If Not (Valid) Then Exit SubMsgBox "Record saved.", vbOKOnly + vbInformation, "Save"

End Sub

This calls the validation routine. If the Valid variable is False upon return from the routine, the data is not valid and we exit the procedure.

4. Save and run the application. Click Edit. Click Edit and blank out the Author Name. Click Save. A message box should appear. Type an invalid numeric value in the Year Born box. Click Save. A new message should be displayed. Click OK and the focus is reset on the Author Name text box, helping the user. Try a valid year and valid name – make sure they are accepted.

58

Page 59: VB Advanced Exercises

5. After typing a new Author name, to type a Year Born, you need to click in that text box. This clicking (especially when working with lots of text boxes) is cumbersome. A preferred method would be a programmatic shift of focus. Add this code at the top of the txtYearBorn_KeyPress event:

If KeyAscii = vbKeyReturn Then

txtAuthor.SetFocus Exit SubEnd If

In this code, if the <Enter> key is pressed, the focus is shifted from the Year Born text box to the Author text box (if a valid year is input). This programmatic change of focus is used all the time in database interfaces. Users like to see the focus move when they press <Enter>. It is an additional step in maintaining proper application state. To shift from the Author box to the Year Born box, add this code to the Author_KeyPress event:

Private Sub txtAuthor_KeyPress(KeyAscii As Integer)If KeyAscii = vbKeyReturn Then txtYearBorn.SetFocus

Exit Sub

End IfEnd Sub

6. Save and run the example again. Click Edit. Notice how the focus shifts between the two text boxes as you change the values and press <Enter>. Pressing <Tab> should also change the focus appropriately.

59

Page 60: VB Advanced Exercises

Lesson 12: More tools for enhancing your projectMasked Edit Control

The masked edit control is a data bound control used to prompt users for data input using a mask pattern. It works like a text box, but the mask allows you to specify exactly the desired input format. In a database, this control could be used to prompt for a date, a time, number, or currency value. Or it could be used to prompt for something that follows a pattern, like a phone number or social security number. Use of this control can eliminate many of the entry validation problems mentioned earlier. To load this control, select Components from the Projects menu, then select from the Components dialog box:

Microsoft Masked Edit Control

Masked Edit Properties:

DataField Field in database table, specified by DataSource (or DataMember), bound to masked edit control (DAO or ADO).

DataMember Specifies the Command object establishing the database table (ADO data environment only).

DataSource Specifies the data control (DAO or ADO) or data environment (ADO) the masked edit control is bound to.

Mask Determines the type of information that is input into the control. It uses characters to define the type of input. Check on-line help for mask formatting.

PromptInclude If True, prompt characters included with Text property.Text Contains data entered into the control (including all prompt

characters of the input mask). This is the property bound to the database.

Masked Edit Events:

Change Event called when the data in the control changes. Validation Error Event called when the data being entered by the user does

not match the input mask.

This control features built-in input validation to lessen your tasks as a programmer. We will use the masked edit control in some of our example applications in later chapters.

60

Page 61: VB Advanced Exercises

Example 1 - Masked Edit Control

1. We’ll use the masked edit control to input a phone number. Start a new project. Add a masked edit control to the toolbox. Place a masked edit control and text box on your form.

2. Set the masked edit control Mask property to: (###) ###-####. This mask will allow an area code, followed by a phone number. Your form should look like this:

3. Place this code in the MaskEdBox1_Change event:

Private Sub MaskEdBox1_Change()Text1.Text = MaskEdBox1.TextEnd Sub

4. Save the application and run it. Notice how simple it is to fill in a correct phone number. The text box reflects what is typed in the masked edit control. The Text property of the masked edit control is bound to the database. Change the PromptInclude property to False and note the prompt characters (parentheses, hyphen) are not included in the Text property.

61

Page 62: VB Advanced Exercises

Chart Control

The chart control is an amazing tool. In fact, it’s like a complete program in itself. It allows you to design all types of graphs interactively on your form. Then, at run-time, draw graphs, print them, copy them, and change their styles. To load this control, select Components from the Projects menu, and then select Microsoft Chart Control 6.0.

Chart Control Properties:

Column Returns or sets the current column in the grid of data being charted.

ChartType Establishes the type of chart to display.Data Returns or sets the data in the current row and

column of the grid of data being charted.DataMember Specifies the Command object establishing the database

table (ADO data environment only).DataSource Specifies the data control or data environment the chart

control is bound to.RandomFill Used to fill chart with random values (good for

checking out chart at design-time). Data is normally filled from established array.

Row Returns or sets the current row in the grid of data being charted.

The chart control is valuable. It allows a user a quick overview of any numerical data within a database.

62

Page 63: VB Advanced Exercises

Example– Chart Control

Like an earlier example, this example uses the Northwind Traders database to have a value for charting.

1. Start a new project. Add a chart control (make sure it is the Visual Basic 6 version). Also add a DataEnvironment to the project to link to the NWind.mdb.

2. Add a Command1 to the DataEnvironment and set the SQL to:SELECT ProductName, UnitPrice FROM Products WHERE SupplierID <

5

MSChart1: DataSource DataEnvironment1Data Member Command1

We restrict the SupplierID value to limit the number of records returned.

3. Save the application, then run it. A bar chart of UnitPrice versus ProductName should appear:

If all the labels don’t appear in your example, you need to enlarge the size of the control on your form.

63

Page 64: VB Advanced Exercises

Drag and Drop

1 Start a new project in VB2 Place 5 text boxes onto the form.3 Add some text into 4 text boxes as shown and make the DragMode

Automatic.

4 Copy this text for Text1

Private Sub Text1_DragDrop(Source As Control, X As Single, Y As Single) Text1.Text = Source.TextEnd Sub

5 Run the program and try dragging the contents of the text boxes into Text1.

64

Make the DragMode property Automatic

Destination for drag