Chapter 3
Your first application--a brief tutorial

The quickest way to introduce yourself to Delphi is to write an application. This tutorial guides you through the creation of a program that navigates a marine-life database. After setting up access to the database, you'll write an event handler that opens a standard Save As dialog box, allowing you to write information from the database to a file.

Starting a new application

Before beginning a new application, create a folder to hold the source files.

  1. Create a folder called Marine in the Projects directory off the main Delphi directory.
  2. Open a new project.

    Each application is represented by a project . When you start Delphi, it opens a blank project by default. If another project is already open, choose File|New Application to create a new project.

    When you open a new project, Delphi automatically creates the following files.

    Each form has its own unit and form files.

  3. Choose File|Save All to save your files to disk. When the Save dialog appears, navigate to your Marine folder and save each file using its default name.

    Later on, you can save your work at any time by choosing File|Save All.

    When you save your project, Delphi creates additional files in your project directory. You don't need to worry about them but don't delete them.

When you open a new project, Delphi displays the project's main form, named Form1 by default. You'll create the user interface and other parts of your application by placing components on this form.

Next to the form, you'll see the Object Inspector, which you can use to set property values for the form and components you place on it.

Setting property values

When you use the Object Inspector to set properties, Delphi maintains your source code for you. The values you set in the Object Inspector are called design-time settings.

Adding objects to the form

The Component palette represents components by icons grouped onto tabbed pages. Add a component to a form by selecting the component on the palette, then clicking on the form where you want to place it. You can also double-click a component to place it in the middle of the form.

Add a Table and a StatusBar to the form:

  1. Drop a Table component onto the form.

    Click the Data Access tab on the Component palette. To find the Table component, point at an icon on the palette for a moment; Delphi displays a Help hint showing the name of the component.

    When you find the Table component, click it once to select it, then click on the form to place the component. The Table component is nonvisual, so it doesn't matter where you put it. Delphi names the object Table1 by default. (When you point to the component on the form, Delphi displays its name--Table1--and the type of object it is--TTable.)

    Each Delphi component is a class; placing a component on a form creates an instance of that class. Once the component is on the form, Delphi generates the code necessary to construct an instance object when your application is running.

  2. Set the DatabaseName property of Table1 to DBDEMOS. (DBDEMOS is an alias to the sample database that you're going to use.)

    Select Table1 on the form, then choose the DatabaseName property in the Object Inspector. Select DBDEMOS from the drop-down list.

  3. Double-click the StatusBar component on the Win32 page of the Component palette. This adds a status bar to the bottom of the application.

  4. Set the AutoHint property of the status bar to True. The easiest way to do this is to double-click on False next to AutoHint in the Object Inspector. (Setting AutoHint to True allows Help hints to appear in the status bar at runtime.)

         

Connecting to a database

The next step is to add database controls and a DataSource to your form.

  1. From the Data Access page of the Component palette, drop a DataSource component onto the form. The DataSource component is nonvisual, so it doesn't matter where you put it on the form. Set its DataSet property to Table1.
  2. From the Data Controls page, choose the DBGrid component and drop it onto your form. Position it in the lower left corner of the form above the status bar, then expand it by dragging its upper right corner.

    If necessary, you can enlarge the form by dragging its lower right corner. Your form should now resemble the following figure.

  3. Set DBGrid properties to align the grid with the form. Double-click Anchors in the Object Inspector to display akLeft, akTop, akRight, and akBottom; set them all to True.
  4. Set the DataSource property of DBGrid to DataSource1 (the default name of the DataSource component you just added to the form).

    Now you can finish setting up the Table1 object you placed on the form earlier.

  5. Select the Table1 object on the form, then set its TableName property to BIOLIFE.DB. (Name is still Table1.) Next, set the Active property to True.

    When you set Active to True, the grid fills with data from the BIOLIFE.DB database table. If the grid doesn't display data, make sure you've correctly set the properties of all the objects on the form, as explained in the instructions above. (Also verify that you copied the sample database files into your ...\Borland Shared\Data directory when you installed Delphi.)

    The DBGrid control displays data at design time, while you are working in the IDE. This allows you to verify that you've connected to the database correctly. You cannot, however, edit the data at design time; to edit the data in the table, you'll have to run the application.

  6. Press F9 to compile and run the project. (You can also run the project by clicking the Run button on the Debug toolbar, or by choosing Run from the Run menu.)

In connecting our application to a database, we've used three components and several levels of indirection. A data-aware control (in this case, a DBGrid) points to a DataSource object, which in turn points to a dataset object (in this case, a Table). Finally, the dataset (Table1) points to an actual database table (BIOLIFE), which is accessed through the BDE alias DBDEMOS. (BDE aliases are configured through the BDE Administrator.)

This architecture may seem complicated at first, but in the long run it simplifies development and maintenance. For more information, see "Developing database applications" in the Developer's Guide or online Help.

Adding support for a menu and a toolbar

When you run your project, Delphi opens the program in a window like the one you designed on the form. The program is a full-fledged Windows application, complete with Minimize, Maximize, and Close buttons and a Control menu. You can scroll through the BIOLIFE data in the grid.

Though your program already has a great deal of functionality, it still lacks many features usually found in Windows applications. For example, most Windows applications implement menus and toolbars to make them easy to use.

In this section, you'll prepare your application for additional graphical-interface elements by setting up an ActionList component. While you can create menus, toolbars, and buttons without using action lists, action lists simplify development and maintenance by centralizing responses to user commands.

  1. Click the X in the upper right corner to close the application and return to the design-time view of the form.
  2. From the Win32 page of the Component palette, drop an ImageList onto the form. This is a nonvisual component, so it doesn't matter where you place it. The ImageList will contain icons that represent standard actions like Cut and Paste.
  3. From the Standard page of the Component palette, drop an ActionList onto the form. This is another nonvisual component.
  4. Set the action list's Images property to ImageList1.
  5. Double-click the action list to display the Action List editor.

  6. Right-click on the Action List editor and choose New Standard Action. The Standard Actions list box is displayed.
  7. Select the following actions: TDataSetFirst, TDataSetLast, TDataSetNext, TDataSetPrior, TEditCopy, TEditCut, and TEditPaste. (Use the Ctrl key to select multiple items.) Then click OK.

  8. Click on the X to close the Action List editor.

You've added standard actions. Now you're ready to add the menu and toolbar.

Adding a menu

In this section, you'll add a main menu bar with three drop-down menus--File, Edit, and Record--and you'll add menu items to each one using the standard actions in the action list.

  1. From the Standard page of the Component palette, drop a MainMenu component onto the form. It doesn't matter where you place it.
  2. Set the main menu's Images property to ImageList1.
  3. Double-click the menu component to display the Menu Designer.

  4. Type &File to set the Caption property of the first top-level menu item and press Enter.

  5. Type &Save and press Enter to create a Save menu item under File.
  6. Type a hyphen in the next item under the File menu and press Enter to create a separator bar on the menu.
  7. Type E&xit and press Enter to create an Exit menu item under File.
  8. Click on the second top-level menu item (to the right of File), type &Edit, and press Enter. The first menu item under Edit is selected.

  9. Click on the third top-level menu item (to the right of Edit), type &Record as its caption, and press Enter. The menu item under Record is selected.

  10. Click on the X to close the Menu Designer.

Press F9 to run your program and see how it looks.

Close the application when you're ready to continue.

Adding a toolbar

  1. On the Win32 page of the Component palette, double-click the ToolBar to add it to the form.

  2. Add buttons to the toolbar.

  3. Assign actions to the first set of buttons.

  4. Assign actions to the second set of buttons.

    Here's how it looks:

  5. Press F9 to compile and run the project.

Check out the toolbar. The First, Prior, Next, and Last buttons work. Select text within a cell in the grid; the Cut, Copy, and Paste buttons work as well.

Close the application when you're ready to continue.

Displaying images

Each record in the BIOLIFE database has a picture associated with it. In this section, we'll expand our application to display pictures.

  1. From the Standard page of the Component palette, drop a Panel component onto the form below the toolbar. Delphi names this Panel1 by default.
  2. In the Object Inspector, delete the Panel1 string from the panel's Caption property. Leave the Caption property blank.
  3. Align Panel1 to the top of the form by setting its Align property to alTop. Next, drag the bottom of the panel down so it fills the portion of the form between the toolbar and the grid.

  4. Set the panel's color to clBlue.
  5. From the Data Controls palette page, drop a DBImage component on top of Panel1 and set its Align property to alRight. Size the DBImage by dragging out its left side so your form resembles the one shown in the following figure.

  6. Set the DataSource property of DBImage to DataSource1. Then set its DataField property to Graphic. (In the Object Inspector, the drop-down list next to DataField shows the fields in the BIOLIFE table. Graphic is one of the field names.)

    As soon as you set DataField to Graphic, the DBImage component displays the image of a fish corresponding to the first record of the table. This shows that you have correctly hooked up to the database.

  7. Press F9 to compile and run your application.

Close the application when you're ready to continue.

Adding text and memo objects

In this section, you'll add two components that display individual text fields from the database.

  1. Select Panel1.
  2. From the Data Controls page of the Component palette, drop a DBMemo component onto Panel1 and position it so it occupies the upper left corner of the panel (below the menus and toolbar).
  3. Resize the DBMemo by dragging its lower right corner. Extend the right edge of the DBMemo until it touches the left edge of the DBImage. Extend the bottom of the DBMemo to within a half inch or so of the bottom of Panel1.
  4. In the Object Inspector, set the following properties for the DBMemo.

  5. Drop a DBText component on Panel1 under the DBMemo object. Enlarge the DBText so it fills the area under the DBMemo, then set its properties as follows.

  6. Customize the Font property of the DBText component using the Font editor.

    The Font editor is a property editor that you can access through the Object Inspector. Select the Font property in the Object Inspector; an ellipsis button appears on the right side of the property setting. Click the ellipsis button to display the Font editor.

    Modify the following DBText settings using the Font editor, then click OK.

  7. Compile and run your application by pressing F9.

You can view and edit the data in the DBMemo component. The DBText component displays data for reading only.

Close the application when you're ready to continue.

Writing an event handler

Up to this point, you've developed your application without writing a single line of code. By using the Object Inspector to set property values at design time, you've taken full advantage of Delphi's RAD environment. In this section, however, you'll write procedures called event handlers that respond to user input while the application is running. You'll connect the event handlers to menu items, so that when a menu item is selected your application executes the code in the handler.

  1. From the Dialogs page of the Component palette, drop a SaveDialog component onto the form. This is a nonvisual component, so it doesn't matter where you place it. Delphi names it SaveDialog1 by default. (When SaveDialog's Execute method is called, it invokes a standard Windows dialog for saving files.)
  2. From the menu on your form, choose File|Save. Delphi creates a skeleton event handler for the event that occurs at runtime when the user selects Save from the File menu. The Code editor opens with the cursor inside the event handler.

    This event handler is attached to the OnClick event of the main menu's first menu item. The menu item is an instance of the class TMenuItem, and OnClick is its default event. Hence the Save1Click method is a default event handler.

  3. Complete the event handler by adding the code shown below in the var section and between the outermost begin and end.
      procedure TForm1.Save1Click(Sender: TObject);
      var 
        i: integer;
      begin 
        SaveDialog1.Title := Format('Save info for %s', [DBText1.Field.AsString]);
        if SaveDialog1.Execute then
        begin
          with TStringList.Create do
          try
            Add(Format('Facts on the %s', [DBText1.Field.AsString]));
            Add(#13#10);
            for i := 1 to DBGrid1.FieldCount-3 do
            Add(Format('%s : %s',
              [DBGrid1.Fields[i].FieldName,
              DBGrid1.Fields[i].AsString]));
            Add(Format(#13#10+'%s'+#13#10,[DBMemo1.Text]));
            SaveToFile(SaveDialog1.FileName);
          finally
            Free;
          end;
        end;
      end;
    

    This event handler calls the Execute method in the SaveDialog component. When the dialog box opens and the user specifies a file name, it saves fields from the current database record into a file.

     
    
  4. To add code for the Exit command, choose File|Exit. Delphi generates another skeleton event handler and displays it in the editor.
      procedure TForm1.Exit1Click(Sender: TObject);
      begin
       
      end;
    

    Right where the cursor is positioned (between begin and end), type

      Close;
    
  5. Choose File|Save All to save your work. Then press F9 to run the application.

You can exit the program using the now functional File|Exit command.

Most components on the Component palette have events, and most components have a default event. A common default event is OnClick, which gets called whenever the component is clicked; for example, if you placed a Button component (TButton) on a form, you would almost certainly write an OnClick event handler for it. When you double-click certain objects on a form, Delphi creates a skeleton handler for the default event.

You can also access all of a component's events through the Object Inspector. Select an object on a form, then click the Events tab on the object Inspector; you'll see a list of the object's events. To create a skeleton handler for any event, double-click in the space to its right.

For more information about events and event handlers, see "Developing the application user interface" in the Developer's Guide or online Help.