Home > Articles > Data

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Creating Client Datasets

Using client datasets in your application is similar to using any other type of dataset because they derive from TDataSet.

You can create client datasets either at design-time or at runtime, as the following sections explain.

Creating a Client Dataset at Design-Time

Typically, you create client datasets at design-time. To do so, drop a TClientDataSet component (located on the Data Access tab) on a form or data module. This creates the component, but doesn't set up any field or index definitions. Name the component cdsEmployee.

To create the field definitions for the client dataset, double-click the TClientDataSet component in the form editor. The standard Delphi field editor is displayed. Right-click the field editor and select New Field... from the pop-up menu to create a new field. The dialog shown in Figure 3.1 appears.

Figure 3.1 Use the New Field dialog to add a field to a dataset.

If you're familiar with the field editor, you notice a new field type available for client datasets, called Aggregate fields. I'll discuss Aggregate fields in detail in the following chapter. For now, you should understand that you can add data, lookup, calculated, and internally calculated fields to a client dataset—just as you can for any dataset.

The difference between client datasets and other datasets is that when you create a data field for a typical dataset, all you are doing is creating a persistent field object that maps to a field in the underlying database. For a client dataset, you are physically creating the field in the dataset along with a persistent field object. At design-time, there is no way to create a field in a client dataset without also creating a persistent field object.

Data Fields

Most of the fields in your client datasets will be data fields. A data field represents a field that is physically part of the dataset, as opposed to a calculated or lookup field (which are discussed in the following sections). You can think of calculated and lookup fields as virtual fields because they appear to exist in the dataset, but their data actually comes from another location.

Let's add a field named ID to our dataset. In the field editor, enter ID in the Name edit control. Tab to the Type combo box and type Integer, or select it from the drop-down list. (The component name has been created for you automatically.) The Size edit control is disabled because Integer values are a fixed-length field. The Field type is preset to Data, which is what we want. Figure 3.2 shows the completed dialog.

Figure 3.2 The New Field dialog after entering information for a new field.

Click OK to add the field to the client dataset. You'll see the new ID field listed in the field editor.

Now add a second field, called LastName. Right-click the field editor to display the New Field dialog and enter LastName in the Name edit control. In the Type combo, select String. Then, set Size to 30—the size represents the maximum number of characters allowed for the field. Click OK to add the LastName field to the dataset.

Similarly, add a 20-character FirstName field and an Integer Department field.Finally, let's add a Salary field. Open the New Field dialog. In the Name edit control, type Salary. Set the Type to Currency and click OK. (The currency type instructs Delphi to automatically display it with a dollar sign.)

If you have performed these steps correctly, the field editor looks like Figure 3.3.

Figure 3.3 The field editor after adding five fields.

That's enough fields for this dataset. In the next section, I'll show you how to create a calculated field.

Calculated Fields

Calculated fields, as indicated previously, don't take up any physical space in the dataset. Instead, they are calculated on-the-fly from other data stored in the dataset. For example, you might create a calculated field that adds the values of two data fields together. In this section, we'll create two calculated fields: one standard and one internal.

NOTE

Actually, internal calculated fields do take up space in the dataset, just like a standard data field. For that reason, you can create indexes on them like you would on a data field. Indexes are discussed later in this chapter.

Standard Calculated Fields

In this section, we'll create a calculated field that computes an annual bonus, which we'll assume to be five percent of an employee's salary.

To create a standard calculated field, open the New Field dialog (as you did in the preceding section). Enter a Name of Bonus and a Type of Currency.

In the Field Type radio group, select Calculated. This instructs Delphi to create a calculated field, rather than a data field. Click OK.

That's all you need to do to create a calculated field. Now, let's look at internal calculated fields.

Internal Calculated Fields

Creating an internal calculated field is almost identical to creating a standard calculated field. The only difference is that you select InternalCalc as the Field Type in the New Field dialog, instead of Calculated.

Another difference between the two types of calculated fields is that standard calculated fields are calculated on-the-fly every time their value is required, but internal calculated fields are calculated once and their value is stored in RAM. (Of course, internal calculated fields recalculate automatically if the underlying fields that they are calculated from change.)

The dataset's AutoCalcFields property determines exactly when calculated fields are recomputed. If AutoCalcFields is True (the default value), calculated fields are computed when the dataset is opened, when the dataset enters edit mode, and whenever focus in a form moves from one data-aware control to another and the current record has been modified. If AutoCalcFields is False, calculated fields are computed when the dataset is opened, when the dataset enters edit mode, and when a record is retrieved from an underlying database into the dataset.

There are two reasons that you might want to use an internal calculated field instead of a standard calculated field. If you want to index the dataset on a calculated field, you must use an internal calculated field. (Indexes are discussed in detail later in this chapter.) Also, you might elect to use an internal calculated field if the field value takes a relatively long time to calculate. Because they are calculated once and stored in RAM, internal calculated fields do not have to be computed as often as standard calculated fields.

Let's add an internal calculated field to our dataset. The field will be called Name, and it will concatenate the FirstName and LastName fields together. We probably will want an index on this field later, so we need to make it an internal calculated field.

Open the New Field dialog, and enter a Name of Name and a Type of String. Set Size to 52 (which accounts for the maximum length of the last name, plus the maximum length of the first name, plus a comma and a space to separate the two).

In the Field Type radio group, select InternalCalc and click OK.

Providing Values for Calculated Fields

At this point, we've created our calculated fields. Now we need to provide the code to calculate the values. TClientDataSet, like all Delphi datasets, supports a method named OnCalcFields that we need to provide a body for.

Click the client dataset again, and in the Object Inspector, click the Events tab. Double-click the OnCalcFields event to create an event handler.

We'll calculate the value of the Bonus field first. Flesh out the event handler so that it looks like this:

procedure TForm1.cdsEmployeeCalcFields(DataSet: TDataSet);
begin
 cdsEmployeeBonus.AsFloat := cdsEmployeeSalary.AsFloat * 0.05;
end;

That's easy—we just take the value of the Salary field, multiply it by five percent (0.05), and store the value in the Bonus field.

Now, let's add the Name field calculation. A first (reasonable) attempt looks like this:

procedure TForm1.cdsEmployeeCalcFields(DataSet: TDataSet);
begin
 cdsEmployeeBonus.AsFloat := cdsEmployeeSalary.AsFloat * 0.05;
 cdsEmployeeName.AsString := cdsEmployeeLastName.AsString + ', ' +
 cdsEmployeeFirstName.AsString;
end;

This works, but it isn't efficient. The Name field calculates every time the Bonus field calculates. However, recall that it isn't necessary to compute internal calculated fields as often as standard calculated fields. Fortunately, we can check the dataset's State property to determine whether we need to compute internal calculated fields or not, like this:

procedure TForm1.cdsEmployeeCalcFields(DataSet: TDataSet);
begin
 cdsEmployeeBonus.AsFloat := cdsEmployeeSalary.AsFloat * 0.05;

 if cdsEmployee.State = dsInternalCalc then
 cdsEmployeeName.AsString := cdsEmployeeLastName.AsString + ', ' +
  cdsEmployeeFirstName.AsString;
end;

Notice that the Bonus field is calculated every time, but the Name field is only calculated when Delphi tells us that it's time to compute internal calculated fields.

Lookup Fields

Lookup fields are similar, in concept, to calculated fields because they aren't physically stored in the dataset. However, instead of requiring you to calculate the value of a lookup field, Delphi gets the value from another dataset. Let's look at an example.

Earlier, we created a Department field in our dataset. Let's create a new Department dataset to hold department information.

Drop a new TClientDataSet component on your form and name it cdsDepartment. Add two fields: Dept (an integer) and Description (a 30-character string).

Show the field editor for the cdsEmployee dataset by double-clicking the dataset. Open the New Field dialog. Name the field DepartmentName, and give it a Type of String and a Size of 30.

In the Field Type radio group, select Lookup. Notice that two of the fields in the Lookup definition group box are now enabled. In the Key Fields combo, select Department. In the Dataset combo, select cdsDepartment.

At this point, the other two fields in the Lookup definition group box are accessible. In the Lookup Keys combo box, select Dept. In the Result Field combo, select Description. The completed dialog should look like the one shown in Figure 3.4.

Figure 3.4 Adding a lookup field to a dataset.

The important thing to remember about lookup fields is that the Key field represents the field in the base dataset that references the lookup dataset. Dataset refers to the lookup dataset. The Lookup Keys combo box represents the Key field in the lookup dataset. The Result field is the field in the lookup dataset from which the lookup field obtains its value.

To create the dataset at design time, you can right-click the TClientDataSet component and select Create DataSet from the pop-up menu.

Now that you've seen how to create a client dataset at design-time, let's see what's required to create a client dataset at runtime.

Creating a Client Dataset at Runtime

To create a client dataset at runtime, you start with the following skeletal code:

var
 CDS: TClientDataSet;
begin
 CDS := TClientDataSet.Create(nil);
 try
 // Do something with the client dataset here
 finally
 CDS.Free;
 end;
end;

After you create the client dataset, you typically add fields, but you can load the client dataset from a disk instead (as you'll see later in this chapter in the section titled "Persisting Client Datasets").

Adding Fields to a Client Dataset

To add fields to a client dataset at runtime, you use the client dataset's FieldDefs property. FieldDefs supports two methods for adding fields: AddFieldDef and Add.

AddFieldDef

TFieldDefs.AddFieldDef is defined like this:

function AddFieldDef: TFieldDef;

As you can see, AddFieldDef takes no parameters and returns a TFieldDef object. When you have the TFieldDef object, you can set its properties, as the following code snippet shows.

var
 FieldDef: TFieldDef;
begin
 FieldDef := ClientDataSet1.FieldDefs.AddFieldDef;
 FieldDef.Name := 'Name';
 FieldDef.DataType := ftString;
 FieldDef.Size := 20;
 FieldDef.Required := True;
end;
Add

A quicker way to add fields to a client dataset is to use the TFieldDefs.Add method, which is defined like this:

procedure Add(const Name: string; DataType: TFieldType; Size: Integer = 0;
 Required: Boolean = False);

The Add method takes the field name, the data type, the size (for string fields), and a flag indicating whether the field is required as parameters. By using Add, the preceding code snippet becomes the following single line of code:

ClientDataSet1.FieldDefs.Add('Name', ftString, 20, True);

Why would you ever want to use AddFieldDef when you could use Add? One reason is that TFieldDef contains several more-advanced properties (such as field precision, whether or not it's read-only, and a few other attributes) in addition to the four supported by Add. If you want to set these properties for a field, you need to go through the TFieldDef. You should refer to the Delphi documentation for TFieldDef for more details.

Creating the Dataset

After you create the field definitions, you need to create the empty dataset in memory. To do this, call TClientDataSet.CreateDataSet, like this:

ClientDataSet1.CreateDataSet;

As you can see, it's somewhat easier to create your client datasets at design-time than it is at runtime. However, if you commonly create temporary in-memory datasets, or if you need to create a client dataset in a formless unit, you can create the dataset at runtime with a minimal amount of fuss.

Accessing Fields

Regardless of how you create the client dataset, at some point you need to access field information—whether it's for display, to calculate some values, or to add or modify a new record.

There are several ways to access field information in Delphi. The easiest is to use persistent fields.

Persistent Fields

Earlier in this chapter, when we used the field editor to create fields, we were also creating persistent field objects for those fields. For example, when we added the LastName field, Delphi created a persistent field object named cdsEmployeeLastName.

When you know the name of the field object, you can easily retrieve the contents of the field by using the AsXxx family of methods. For example, to access a field as a string, you would reference the AsString property, like this:

ShowMessage('The employee''s last name is ' + 
 cdsEmployeeLastName.AsString);

To retrieve the employee's salary as a floating-point number, you would reference the AsFloat property:

Bonus := cdsEmployeeSalary.AsFloat * 0.05;

See the VCL/CLX source code and the Delphi documentation for a list of available access properties.

NOTE

You are not limited to accessing a field value in its native format. For example, just because Salary is a currency field doesn't mean you can't attempt to access it as a string. The following code displays an employee's salary as a formatted currency:

ShowMessage('Your salary is ' + cdsEmployeeSalary.AsString);

NOTE

You could access a string field as an integer, for example, if you knew that the field contained an integer value. However, if you try to access a field as an integer (or other data type) and the field doesn't contain a value that's compatible with that data type, Delphi raises an exception.

Nonpersistent Fields

If you create a dataset at design-time, you probably won't have any persistent field objects. In that case, there are a few methods you can use to access a field's value.

The first is the FieldByName method. FieldByName takes the field name as a parameter and returns a temporary field object. The following code snippet displays an employee's last name using FieldByName.

ShowMessage('The employee''s last name is ' + 
 ClientDataSet1.FieldByName('LastName').AsString);

CAUTION

If you call FieldByName with a nonexistent field name, Delphi raises an exception.

Another way to access the fields in a dataset is through the FindField method, like this:

if ClientDataSet1.FindField('LastName') <> nil then
 ShowMessage('Dataset contains a LastName field');

Using this technique, you can create persistent fields for datasets created at runtime.

var
 fldLastName: TField;
 fldFirstName: TField;
begin
 ...
 fldLastName := cds.FindField('LastName');
 fldFirstName := cds.FindField('FirstName');
 ...
 ShowMessage('The last name is ' + fldLastName.AsString);
end;

Finally, you can access the dataset's Fields property. Fields contains a list of TField objects for the dataset, as the following code illustrates:

var
 Index: Integer;
begin
 for Index := 0 to ClientDataSet1.Fields.Count - 1 do
 ShowMessage(ClientDataSet1.Fields[Index].AsString);
end;

You do not normally access Fields directly. It is generally not safe programming practice to assume, for example, that a given field is the first field in the Fields list. However, there are times when the Fields list comes in handy. For example, if you have two client datasets with the same structure, you could add a record from one dataset to the other using the following code:

var
 Index: Integer;
begin
 ClientDataSet2.Append;
 for Index := 0 to ClientDataSet1.Fields.Count - 1 do
 ClientDataSet2.Fields[Index].AsVariant :=
  ClientDataSet1.Fields[Index].AsVariant;
 ClientDataSet2.Post;
end;

The following section discusses adding records to a dataset in detail.

  • + Share This
  • 🔖 Save To Your Account