Previous page Previous     TOC Contents     Next pageNext


LESSON 9 - Working with a database




Creating the database

In the final 2 lessons in this tutorial, we will be developing a VB Project on "Project Management". The actual database we will be using has already been modelled and created in the tutorial on Database Design and SQL, Lesson 2.

If you haven't read it yet, you should read it now.

If you prefer, you can download the sample database to do the lessons: Download Project Management database.





The Project Management example

ezConsulting Inc. is a company doing IT systems consulting work with a large number of clients. At any given time there are dozens of projects on the go, each employing several employees. In a given period (in this case, weekly) an employee could work on several different projects. In order to track costs and revenues for each project, each employee will submit a timesheet every week showing the number of hours spent on each project. And, since all employees are attached to only one department, costs and revenues can be calculated by department.

It has already been determined that the ProjectMgt database will consist of the following tables:



The first task to be developed in the application consists of table maintenance. For each of the main tables, Employees, Projects and Departments, there have to be ways to add new records, remove records that are no longer needed and change records when appropriate. For example, new employees are hired and other employees leave, the name of a department is changed or a new project is started. Each of these maintenance operations will require a separate form.

Once the maintenance functions are in place, and they have to be (remember: referential integrity dictates that you can't accept a timesheet for a non-existant employee or non-existant project), we can start working on the operational functions, entering timesheets and producing reports. There will be forms for these tasks also.

To make it easier to access the different forms, we will create an Application Menu like we did in the previous lesson. The layout of the Menu form is standard and the code consists of a series of Load and Show statements for the various forms.






Top





Version problems


VB 6 and Access 2000 have compatibility problems. Because VB 6 was released before Access 2000, it does not normally recognize the Access 2000 format. In the example that follows, look at the Connect property of the Data control. If you don't have Access 2000 in the choices when you open "Connect", you have an older version of VB. If you try to connect to an Access 2000 database, you will get a message saying that you have an "Unrecognized database format". If you have an older version of VB6, you will have to get the fix for it. You may be aware that Microsoft regularly publish upgrades to their software products (not that they admit that there are problems with them!). Those upgrades are called Service Packs. Right now, Visual Studio (which includes Visual Basic) is at Service Pack 5. By the time you read this that may have changed. So, to fix your compatibility problem you will have to download the latest Visual Studio Service Pack from Microsoft.

There is a quick fix to the problem, which is what we've done here to save you the trouble of having to download. You can convert your Access 2000 database to Access 97 and use your old VB.

To do that in Access 2000, go to Tools -->Database utilities -->Convert and that will do the trick until you have the time to upgrade VB.

This will also come in handy later when we look at a VB Add-in called Visual Data Manager. Unfortunately, that Add-in does not work at all with Access 2000, even with the VB Service Pack. If you want to use it you will have to convert the database.




The Data Control

To begin the application, we will first create a new form for Projects maintenance: ProjMaint.

The first control we will place on the form, once we've set the basic form properties and saved it, is called the Data Control. It is the object which links a form to a database and allows you to access the fields in the tables making up the database. It's called Data in the Toolbox.

VB provides other objects that allow you to link to databases. ADO (ActiveX Data Objects) are certainly more powerful and more efficient than the Data Control. However, they do require a lot more coding and are more difficult to implement. Also, they are not available in the Standard Edition of VB, only in the Professional and Enterprise Editions. In simple applications, the Data Control, slow as it is, gives you a tool that is easy to implement and will provide most of the functionality you need.



The arrow buttons on the control are used to navigate through the database records:

     First record and Previous

     Next and Last record

The buttons correspond to 4 methods of the DC which you can use when you have to navigate using code. They are:
MoveFirst
MovePrevious
MoveNext
MoveLast
Let's look at the important properties of the Data Control:
  • Name: the name to use in code - Data1 is default - eventually we'll have several data controls on the form - we'll call this one dta_proj.

  • Connect: the kind of database - in this case it's Access - could be Foxpro, dBaseIV, etc.

  • DatabaseName: the name and path of the database the control is connected to.

  • RecordSource: the name of the database table being used.

  • BOFAction and EOFAction: action to take when trying to read before the beginning of file or past the end of file - we'll look at those later.

  • Recordset: this is a run time property, and it's an important one - it represents the result of the query executed to the database - it contains all the records required by this Data Control - when you navigate through the database, you are actually navigating through the recordset, which is then mapped back to the database - that is why the methods of the Data Control refer to the Recordset property.
Next we add the controls needed to look at the fields in the records. In many instances we will need to make changes to the data. Therefore, we'll use a TextBox for each of the fields so that we can both diaplay and enter data as needed. Each TextBox will be a bound control, meaning that it is bound or tied to a specific field from the database. When we navigate through the database using the arrow buttons the content of each TextBox will always reflect the content of the current field. To bind the control to the database field we use its Data properties:

  • DataSource is the name of the Data Control - remember that the DC specifies the name of the database to use and the name of the table to access - tip: enter this one before the DataField.

  • DataField is the name of the field to bind - that field is selected from the content of the table.









Top






Notice that we've also added several buttons to the form. These buttons represent the most common actions we have to perform on the records.

Important note: when you work with bound controls you have to remember that every time you move off a record, the record is automatically modified in the database - every change you make to a TextBox is reflected immediately in the table. That is why there is no Update button - the function is done automatically.

The Reset button allows you to cancel any changes you may have made to the fields - if you modified information and then change your mind about updating it, the Reset will skip the automatic update and return the fields to their original state. This is a method of the Data Control object and is written as:
dta_proj.UpdateControls


There are 2 ways to Add new records to the table:

  • in the Data Control, dta_proj, set the EOFAction property = 2 - this will allow the user to go to Last Record and do a Next, which will add a blank record to the table;

  • use the AddNew method of the Data Control, as in:
    dta_proj.Recordset.AddNew


To Delete the current record, you must use the Delete method followed by a MoveNext to move off the deleted record:
dta_proj.Recordset.Delete
dta_proj.Recordset.MoveNext









Top




Validating data

Before the data you are entering get permanently transfered to the database, you often want to make sure they are correct. That is called data validation. We look here at two simple ways of validating data.

Let's say that the specs for the Projects maintenance part of the application call for three verifications:
  • a budget amount must be entered;

  • the budget amount must not exceed $1,000,000

  • the project end-date cannot be earlier than the start-date.
For the first two we'll use the Validate event of the control. This event is triggered when the CausesValidation property in the TextBox is set to True. Before losing focus, the validation is done. The parameter assigned to the event when it is generated automatically (it's called Cancel) represents the KeepFocus property. If you set it to true in code when you encounter a validation problem, it keeps focus on the current control until the problem is corrected.

The second technique is to use the LostFocus event. When focus moves off the control, you do the validation. If there is an error, you evoke the SetFocus method to put focus back to the control with the error.




Top








Finding a specific record

When you navigate with the arrow buttons or the Move... methods you are necessarily moving one record at a time. Very often there is a need to access a specific record in the database. For example, it might be to change the ending-date for the project called "XYZ Corp. Payroll System".

In this example we assume that the search will be conducted on Project title. It could be on Number or End-date if necessary and it would just involve minor changes to the code. We also assume that the user does not want to enter the full project title and will only input the first few characters; we will therefore make use of the "Like" operator to match the recordset to the search string.

First, we create a new TextBox, called txt_findTitle, to enter the search string. We will give this TextBox the TabIndex 0 because we want it to be the first control read when we look at a record. As soon as we move off the TextBox, the LostFocus event is triggered and checks whether the user has entered a search string or not. If there is no input into the search string, the user can work with the current record in the form. If there is a search string specified, the appropriate record will be loaded into the form.

The FindFirst method of the DC will locate the first occurence in the recordset matching the "content" parameter. If there are more than one records that match, the user then navigates forward using the arrows. The format of the FindFirst method is:
DataControl.Recordset.FindFirst "fieldname = 'searchstring'"

If the fieldname contains a string value, you have to use single quotes to name the searchstring; you can use the other comparison operators in place of the =.

This technique can be adapted to search any field in the recordset for a specific record. There are also FindNext, FindPrevious and FindLast methods for the Data Control recordset.









You might also want to visit this site for
Free Visual Basic 6 tutorials and sample source code examples .









If you haven't found the Visual Basic resource you're looking for,
use our Google Search box for more information.

Google



Top



Home | Tutorials | Contact | Sitemap | Add URL | Privacy policy