Home > Articles > Data

Client Dataset Basics

  • 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

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020