Delphi Starter database tutorials, part 4


Sorting the records

In order to have your books sorted by title, select cdsBooks in the Design view. In the Object Inspector, next to IndexFieldNames, type: Title

Improving the data entry

Entering data directly in the DBGrid is not very safe, because the data is not verified before storing it. Let's improve on this.

Firstly, we don't want the user to change data directly in the grid:
in the Object Inspector, set AutoEdit of dsBooks to False.

Next, we add a panel with a few data controls. Drop a TPanel somewhere below the the DBNavigator. Drop 3 TDBEdit components on the panel. Set the properties of the new components as follows:

TPanelNamepanEdit
 VisibleFalse
TDBEdit1NameedTitle
 DataFieldTITLE
 DataSourcedsBooks
TDBEdit2NameedAuthor
 DataFieldAUTHOR
 DataSourcedsBooks
TDBEdit3NameedISBN
 DataFieldISBN
 DataSourcedsBooks

formBooks

Let's write some source code, using some of the ClientDataSet's events.

  1. Select dsBooks. In the Object Inspector, tab Events, double click next to BeforeEdit.
    Complete the event handler as follows:

    procedure TformBooks.cdsBooksBeforeEdit(DataSet: TDataSet);
    begin
       Grid1.Enabled := False;
       panEdit.Visible := True;
       edTitle.SetFocus;

    end;
  2. Likewise, create an event handler for BeforeInsert and complete the code:

    procedure TformBooks.cdsBooksBeforeInsert(DataSet: TDataSet);
    begin
       Grid1.Enabled := False;
       panEdit.Visible := True;
       edTitle.SetFocus;

    end;
  3. Do the same for event AfterCancel. Code:

    procedure TformBooks.cdsBooksAfterCancel(DataSet: TDataSet);
    begin
       Grid1.Enabled := True;
       panEdit.Visible := False;

    end;
  4. Do the same for event AfterPost. Code:

    procedure TformBooks.cdsBooksAfterPost(DataSet: TDataSet);
    begin
       Grid1.Enabled := True;
       panEdit.Visible := False;

    end;

Note that we didn't provide a TDBEdit for the field ID. That's because we'll let the pogram calculate the ID of each book, starting with '0001' for the first book, next '0002', and so on. We add this functionality in the next part of our tutorial.

Part 3 Database Tutorials - Part 3 Database Tutorials - Part 5 Part 5


Crash Course Delphi  Database tutorials Delphi Starter  FAQ  Tips  Source Code  Downloads  Links