Site hosted by Angelfire.com: Build your free website today!

| Home | Tutorials | Hints & Tips  | Downloads | Links | Guest Book | Vote | Delphi Books | Contact Us | 

Tutorials

Download Lessons in Zip Format

 

Lesson 1     Delphi Basics    by Frank Fortino

 

These Lessons were created using Delphi 3; although most of what I say is also valid for Delphi 4 and D5.

Throughout these Lessons, I will express my opinion on what I think is important and how to write good readable, maintainable programs. I am not saying that this is the best way to do things, I only know what has helped me.

There are so many choices.  That's part of the Problem with Delphi, and the Power of Delphi.
So, to keep this a learning experience and to the point, we can discuss the advantages of different programming styles later.

 

The Style of these Lessons will be somewhat Rambling, I will change topics inside topics.
This is done to conserve time, and to explain things as they come up.
Look at the power of HTML, you can go anywhere, in different ways; lots of choices.

When you program using Delphi you:
    -Should setup the most powerful environment that you can
    -Customize your Tools
    -Set up a Library system to save everything that  you learn
    -Learn good habits

 

There are some little tricks that you can do with Delphi.
    e.g. Hold the Ctrl Key down while grouping Components on your Form
             (Hold the Left mouse button down, creating a box around all the Components you want)
                Selects ALL Components touched
                  -you can then change the Properties of the entire group with ONE click.

     or you can Shift Click on individual Components to group them together.

There are also some consistent ways that Delphi works.
    Right Click:        usually PopsUpMenu
    Double Click::    usually Selects OnClickEvent etc.

 

Delphi has some very powerful Methods and Properties for different Components.

For example:
    ListBox1.Items.LoadFromFile('c:\autoexec.bak');

Items is a TStrings type (So what!)
What you say...
Well TStrings has a Method LoadFromFile that:
    Assigns, Opens, Reads and Closes a Text file; All in 1 Command
    ListBox1.Items.LoadFromFile('c:\autoexec.bak');

ListBox1 now contains all the text in the file 'autoexec.bak'

So, any Component that has a TStrings Property, can use LoadFromFile:

   Memo                Memo1.Lines.LoadFromFile('  ');
   ListBox             ListBox1.Items.LoadFromFile('  ');
   ComboBox        ComboBox1.Items.LoadFromFile('  ');

There is also SaveToFile;  look these up in Delphi's Help (F1)

 

This is a very useful way of getting help.
  Click on a Component,
      Hit F1,
          Select Properties,...

You can also Click on a Component's Property:
    -Put ListBox1 on Form
      -Click on ListBox1
        -In Object Inspector
          -Click on 'Sorted' property (on the left side)
            - Hit F1

Or you could Search for 'TStrings'
    -Help (Menu)
      -Keyword Search
        -Enter 'TStrings'
          - Click Methods
             -Click LoadFromFile

 

Getting started.

The Delphi environment:
            Delphi programs consist of 3 main files (.dpr .pas .dfm)

    .dpr your project file
        - a small program (text file)
       - defines Units in Project

uses
  Forms,
  Unit1 in 'Unit1.pas' {Form1};

1) Initializes Data
2) Builds (creates) the Forms
3) Runs the Application (program)

begin
  Application.Initialize;
  Application.CreateForm(TForm1, Form1);
  Application.Run;
end.

    .pas    1 or more Units (pascal code)
    .dfm    1 or more Form definition files

 

Note:
   - Each Form (.dfm) MUST have a Unit (.pas)
    -You can have Units without a Form (for code only)

    The .dfm file is a special pseudo code file.
    It requires you to use a special program to read this file
        (Point to Form, Right Click, select VIEW AS TEXT)  or Hit Alt F12
            - now you can see your Form creation code:

Example .dfm file:

objectForm1: TForm1
  Left = 200
  Top = 108
  Width = 696
  Height = 480
  Caption = 'Form1'
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'MS Sans Serif'
  Font.Style = []
  PixelsPerInch = 96
  TextHeight = 13
  objectButton1: TButton
    Left = 176
    Top = 116
    Width = 75
    Height = 25
    Caption = 'Button1'
    TabOrder = 0
  end
end

This is a file that you can edit (inside Delphi only) by using VIEW AS TEXT

Normally you DO NOT Edit the .dfm file (as text), you normally put Components on the Form, and Delphi creates the .dfm file for you.

If you edit the .dfm file incorrectly, you can cause some major problems.

To navigate back and forth from the Form(view) to the .dfm(view) use:
    VIEW AS TEXT
    VIEW AS FORM
    or  Alt F12  to toggle back and forth

 

COMMENT:

Try a Mouse Right Click on everything.  Delphi uses this popup menu a lot

use Right Click to:
    - CLOSE the page your on
        (sometimes you have files open that are not part of your program; they are only there to let you easily
          Cut and Paste, code chunks, group of Components)
   - VIEW AS FORM
   - VIEW AS TEXT

 

Developing projects with Delphi

Remember RENAME EVERYTHING AT THE START!

- Use a separate Folder (directory) for each project
    Always start with a NEW APPLICATION and immediately do:

    -File (from Menu)
         -Create New Folder   c:\Delphi3\SysSetup
              -Save Project As   'SysSetup'

    -File   (while in Unit1.pas)
        -Save As    'Main'

Example:

    Project1     // put in a new folder ( ..\SysSetup )
        SAVE AS   SysSetup.dpr

    Form1         MainF   (Rename)
    Unit1           Main.pas  (File / SAVE AS)

   Form2         PriceF   (Rename)
   Unit2           Price   (File / SAVE AS)

Name all your Components when you first use them

    Button1       StartBtn or BStart
    ListBox1     CustList or LBCust

 

Frank's Programming Style

- Small but informative names
        SysSetup.dpr
        XFileName (a Global variable)

- Pick a way to name your components
    My way (which varies)
        T1 : TTable;      // a generic Table that is locally on the Form
                                    or is reused and changed

        BrandTbl : TTable;       // a better way

    or TblBrand : TTable;
        TblCost : TTable
        TPrice : TTable

 

 

Other Programming Hints:

Keep Project versions separated in their own Folders:
    c:\Freedom\Setup\1228

date = 1228   add sub-folders that use the date as their Name

Copy ONLY *.dpr *.pas *.dfm to the New Folder
    Drop the .dpr File on Delphi 3 (Launch it)
       Save Project As     'SysSetup.dpr'

Now you have a perfect copy of your SysSetup.dpr, ...
    without any Hooks or Links to the Old program.

 

Your Tool Bar

I find these tools the best for me (Delphi 3)

Note:
Be sure to Right Click on Tool Bar (Top Left) and Select SHOW HINTS (ON)

To modify your Tool Bar setup:
    Right Click on Tool Bar and Select PROPERTIES
        Drag and drop Icons Off the ToolBar
        Drag and drop Icons from List onto ToolBar

Be sure to Right Click on Component Palette (Top Right) and Select SHOW HINTS (ON)

 

Good Programming Habits:

    1) Capitalize the first letter of each new word (in a name)
            avoid underscores (I think they are redundant) New_Data should be NewData

    2) Indent 2 or 3 spaces
            Line up ALL begin ends

    for x:=1 to 22 do
    begin
      if y>32 then ....
    end;
    ----------------

if ... then
begin
  ...
end

else if ... then
begin
  ...
end;

 

 

TURN OFF THE CODE OPTIMIZATION

    -Project (menu)
      -Options
        -Compiler (tab)
          -Optimization TURN OFF

    -Check Default (CheckBox)
    -OK

The Code Optimizer is TOO Smart sometimes, and does not let you set Breakpoints (to stop your code).

I will have a Lesson on Breakpoints and Debugging your Code later.

You can learn a lot from using Breakpoints
    - You can see the sequence that Delphi executes code
    - You can Watch your Data (by moving the mouse over a variable)
         or in a Watch Window

 

New Subject: Form Stuff

Form Events
    OnCreate
    OnShow
    OnActivate

Form Properties
    Visible

They all control when a Form is Created, Visible, Open, Closed, Active
What is the Difference between them, and How and When do you use them.

A Form is Created first.
It's Only Created one time in the .dpr File

  begin
    Application.Initialize;
    Application.CreateForm(TForm1, Form1); // Right Here Form1 is Created
    Application.Run;
  end.

Form1.Show;   // is a method that makes the Form Visible (Open);

Form1.Visible:=True; // Also, makes a Form Visible

Form1.Close;  // Makes the Form not Visible
    (If Form1 is your Main Form, this will Close (Quit) your Project)

So, don't Close Form1, just set
    Form1.Visible:=False;

 

IMPORTANT KEYS

  F1     = Help
  F12   = Toggle Form / Unit
      Alt F12   = Toggle Form/.dfm

   F7  = Single Step (Step into Procedures)
   F8  = Single Step (Step over Procedures)
   F9  = Run Program
   ^F2  = Reset (Stop) Program

 

Delphi Quirks

    Be careful, Delphi does a lot behind the scenes.
        (this is not a complete example - it's only trying to show you how a Problem can occur)

    That's why I say to name everything, Before you start coding  or Linking other Components.

    For Example:
        Working with Tables and DBGrids
        If you Right Click a Table
            -Select FIELDS EDITOR
                -Right Click
                    -Add Fields
                          - ...
    Then you Link a DBGrid to that Table
    Then you edit or delete some Table Fields.

    Watch out ---
        Delphi still thinks you have fields that you deleted.

    You have to Remove the Table and DBGrid; and start over to break those Links.

    Sometimes it's hard to go backwards in Delphi.

 

COMMENT:

    Programming with C++ is like programming with Sand.
        You can build Bricks (in hours)
        You can use Bricks to build Walls (in days)
        You can use Walls to build Rooms (in weeks)
        You can use Rooms to Build Houses (in months)

    With Delphi you are programming with Rooms
        You can use Rooms to Build Houses (in hours)

 

Keeping your own Help Library

You learn so much so fast in Delphi, that you should have a simple and quick way to save what you learned:
    -In example programs
    -In Text files and Code Snippets

You learn so much, that you get lost. When you come back to a subject (e.g.  ListBoxes) you forget some the details of how to use a ListBox and how to use certain properties.

You did it before, but how?
    You will be in this position a lot if you don't save things as you learn them.

Always have a text editor (like EditPad) open on your Tray, so that you can cut and paste code snippets from Help examples or your own code, into a text file and save it as (e.g.   'ListBoxLoading.txt')

Also, a way to learn about a new Component that you've not used before; is to create a new project with just that Component (say: ComboBox1) with a few Buttons that  change Properties of ComboBox1 or call Methods of ComboBox1.

Play with the program a while, then save the program
    (.dpr .pas .dfm) files in its own folder (e.g.    'c:\D3 Help\ComboBoxes')

Believe me, these little help files that you create (text and programs), will accumulate and give you a nice Library of very useful stuff.

That's what a Power Programmer is (He has lots of Stuff to copy, cut and paste; to create projects)

So get some good habits now, and you will not take any steps backward.
    It is very frustrating , to have to look up something,  that you knew how to do before.

NOTE:  I've added the HELPVIEWER program, on my site, to help you manage and use your help file snippets. Try it


 

Some OOP Basics

    Parent
    Owner
    Sender

    What is what?

    Difference between Owner and Parent:
    If you have a Form1
        On Form1 you place a Panel1
            On Panel1 you place Button1

    Form1 is the Parent of Panel1
    Panel1 is the Parent of Button1
    Form1 is the Owner of both Panel1 and Button1

    Form1 owns everything, Form1 is the Owner and Parent of Panel1

    Form1 is the Owner of Button1, but Button1's Parent is Panel1 (because Button1 is On (Held by) Panel1).

    The Owner is important, because when Form1 is Created by the .dpr File:
        Application.CreateForm(TForm1, Form1);

    Form1 now exists in Memory (takes up space)
    When Form1 is Created, so is Panel1 and Button1 because Form1 is the Owner.

    When Form1 is Closed (you exit your Project) the Memory used by Form1, Panel1 and Button1 is Freed (put back in the Heap).

    Have you heard of a Memory Leak?
    A Memory Leak is when Form1 Closes, but it does not Free the RAM used by Button1. This would be a BUG in Delphi (which is not the case).

    So, now every time you Create Form1 and Close it, it would use up and waste (not free up) the RAM used by Button1.

    Only a few Components can be Parents
        They can contain other Components

    A Button cannot contain another Button, so it cannot be a Parent

    Only a few Components can hold other Components; the common ones are:
        Form
        Panel
        GroupBox
        NoteBook (Delphi 2)
        PageControl
        TabSheets

    How is the Parent Property used?
    Button1 has Panel1 as its Parent, so Button1 gets some of its Properties from Panel1.

        i.e. If you change the Font to Bold on the Panel what happens?
                Yep the Font changes for Panel1 and Button1.

If you look at a Button's Properties in the ObjectInspector you will see a Property named ParentFont set to TRUE
If you change this to False, then Button1 will not get its Font from Panel1.

I hope this helps a little.


 

One point to my readers.
Don't worry if you don't understand everything that I say here.
I am jumping around and not explaining(in detail) how and why.

After you work with Delphi a while you will start thinking differently, and you will see the same structures used over and over; then they will become easy and almost trivial.

For all of us Mainline (DOS, TP5, C++) programmers that are used to a mainline that loops. Delphi does not have a mainline; or let me say that you do not normally work with the mainline.   The mainline is controlled by Windows95 running in the background, processing key hits and mouse movements.

I really don't miss a mainline; it was a pain anyway.

Delphi is Event driven; that means, that nothing happens until something happens (good logic???) (e.g. a key is hit etc.)


 

New Topic: Delphi's initial mainline sequence of events:

1) The .dpr program runs, and Creates Forms (and everything on the Forms)
    (creating means - memory is allocated for each object)

    In Delphi this is called INSTANTIATED (strange word), it just means that the Form is now allocated, (uses) RAM memory space.

2) The following Events are called (run)
    Form OnCreate     =>    .FormCreate( )     // remember they drop the 'On' ???
    Form OnShow      =>    . FormShow( )

3) Then your program waits for the user to do something (Click the mouse,...)

Q: If you want to Initialize some variables, only once, when the program first runs; where do you put the code?
    Ans: You Initialize vars in the FormCreate( ) Event; since it happens before anything else; and it only happens once.

There are other places to Initialize vars, but FormCreate( ) is all you need for now.


 

Sender ????

Almost every Component has Events that are Triggered by the User Clicking the Mouse, or Hitting Keys.

If you Click on Button1, it calls its:

procedure TForm1.Button1Click(Sender: TObject);
                                |               |            | -- OnClick Event(they always leave off the On?)
                                |               |
                                |               | --- This procedure was called by Button1 being Clicked
                                |
                                |- TForm1 is the Owner of Button1; so it's (TForm1.Button1)

The Sender(Caller) of this procedure is Button1

You can use the Sender (Parameter), which is of generic type TObject
    Everything in Delphi is of type TObject.

You could have another Component (e.g. an Edit1 Component) use this same procedure for its OnClick Event (because you don't want to write another procedure for Edit1).

Edit1 is of type TEdit and TObject
Button1 is of type TButton and TObject

So the Sender Parameter sent by Button1 or Edit1 when they are Clicked, can be either a TEdit (from Edit1) or a TButton (form Button1).

That's why the Sender (param) is defined as a TObject, so it can be anything a TButton, TEdit ... Get it.

Inside the OnClick procedure you can then determine what Component called it:

 

Shared OnClick Event Procedure (used by both Button1 and Edit1)

procedure TForm1.Button1Click(Sender: TObject);
begin
  if (Sender is TButton) then Pane1.Color:=clRed      \\ Click came from Button
  else if (Sender is TEdit) then Panel1.Color:=clLime \\ Click came from Edit
end;

 

Separate OnClick Events

procedure TForm1.Button1Click(Sender: TObject);
begin
  Pane1.Color:=clRed
end;

procedure TForm1.Edit1Click(Sender: TObject);
begin
  Pane1.Color:=clLime
end;

 

 

Learning Delphi on your own:

Books with CD's are a great resource to search for examples of code, for a new component or property that you want to use.

In Win95 Hit START
    -Find
        -File and Folders
            -File Name *.pas
                -Containing Text .LOCATE(

This will search all *.pas files for examples that use .LOCATE(
Then drop each one of the found files on your editor (EditPad) and search for .LOCATE (and see if it helps you).

It's a great resource.
The Delphi 3 CD also has some good examples.

 

DELPHI NOTE:

Watch out, Delphi is different, your code can fool you.

Say, you want to hit a Button that turns a Panel Red for 3 seconds, then turns it to Green
So you write the OnClick event for Button1:

procedure TForm1.Button1Click(Sender: TObject);
begin
  Panel1.Color:=clRed;
  sleep(3000); // delays 3000 msec
  Panel1.Color:=clGreen;
end;

-----

You Run the program, Click the Button; What happens?

Nothing happens for 3 seconds then the Panel turns Green.
    What happened to Red?

Hah, I say.

Well guess what, when you are in the Button1Click procedure, you do not repaint the Form UNTIL YOU EXIT the procedure.

While you are in the procedure, you see nothing changing on your Form; unless you say the magic words!
  Application.ProcessMessages;

procedure TForm1.Button1Click(Sender: TObject);
begin
  Panel1.Color:=clRed;
  Application.ProcessMessages; // this will repaint your Form
  sleep(3000);
  Panel1.Color:=clGreen;
end;

Now you hit the Button, the Panel turns Red for 3 seconds, then turns Green.

So, what have we learned form this.

If you are inside a procedure and you want things to change on your Form, so that the user can see them; you have to use:
    Application.ProcessMessages;

At all the places where you want the Form to change.

This gives you a simple way of doing quasi MULTITASKING in Delphi.

 

Another way to do simple MULTITASKING (with a Timer):

By the way Delphi can use Threads to do multitasking, but they are a little tricky
    -Application.ProcessMessages; technique (above)
    -or the Timer technique (that I am about to explain)

A Timer Component, has an INTERVAL Property (with a default setting of 1000 (1 sec)), and an OnTimer Event that is triggered (every 1 second)

Start with a New Application
    - Put a Panel1 on your Form
    - Put a Timer1 on the Form (it looks like a clock)
    - Double Click the (right side of) OnTimer Event in the ObjectInspector

and write the following:

procedure TForm1.Timer1Timer(Sender: TObject);
begin
  if Panel1.Color=clRed then
    Panel1.Color:=clGreen
  else Panel1.Color:=clRed;
end;

Run the program. The Panel turns Red then Green every 1 second.

So, now you have a mini-mainline that loops every 1 second.

WOWWW!!!

 

DELPHI NOTE:

You might not know this but ALMOST EVERYTHING in Delphi is a pointer; but you never see the word pointer used anywhere.

It's all done behind the scenes.

It's not like C++ or TP with **char @data ^xyz or whatever.

Delphi is beautiful, Delphi is grand.  Thank you God.

Delphi even has a variable type called a VARIANT that is everything;
    a char, word, string[3000], real, double, currency, boolean
It changes itself into whatever type you need.

e.g.
    XVar : variant;

This is all legal:
    begin
      XVar:='Frank'; // a string
      XVar:=True; // boolean
      XVar:=244.34567; // float,real
    end;

I might discuss variants later; but I don't use them much or recommend them.

 

Change of Topic:

Delphi uses multiple names for floats depending on where you are:
    float
    real
    double
    currency
    number
    money
    - and more

 

Power Programming Techniques:

Delphi lets you do Cutting and Pasting of Components, Groups of Components, Forms ...
    Ctrl X   =  CUT
    Ctrl C   =  COPY
    Ctrl V   =  PASTE

This can really improve the speed that you program, and saves a lot of busy work.

So, experiment with Cutting and Pasting and learn how to use it. What it does and doesn't do.
Put a Button on a Form, and copy it(^C, ^V)

Also, try adding another Unit to your Project.
    -Project Mgr (on Toolbar)
        - Add
            - Select Folder/File Name
                -Open

Then link the 2 Units together by adding:
    in Unit1 (after Implementation)
    uses Unit2;

    in Unit2(after Implementation)
    uses Unit1;

Now in Unit1, you can call procedures in Unit2:
   Form2.Panel1.Color:=clRed;

What is going on?

I told Unit1 to use Unit2; why don't I call stuff in Unit2 as:
   Unit2.Panel1.Color:=clRed;     // WRONG

You DON'T, you call Components in Unit2 by referencing Unit2's Form (Form2), because Form2 is the owner.  That's Delphi.
   Form2.Panel1.Color:=clRed;     // CORRECT

 

Note: WATCH OUT

When you Add a Unit/Form (e.g. Sales.pas) that you used somewhere else, to your new project, Delphi DOES NOT make a copy of Sales.pas.

Delphi has a path to the original Sales.pas and any changes you make to Sales.pas will change the original. OOOPs GOT YA!!
    (that's why it's called OOP programming! Aha)

How do I work with a copy of Sales.pas and not the original?

2 ways:
    1)-File (while viewing Sales.pas in your new project)
        -Save As
        -Change the Folder and save Sales.pas in your new Project Folder.

     2) Before you start, you copy Sales.pas and Sales.dfm to your new Project Folder.

 

Also, you can create your own Components and put them on your Component Palette, without writing any code.

These are called COMPONENT TEMPLATES

THIS ONE IS GREAT

Blank Form
Add a Panel
Put some Buttons on the Panel
Point to the Panel
    -Component(Menu)
        -Create Component Template
            -Change COMPONENT NAME to P1
                -OK

Look at your Component Palette (Standard Tab)
You now have a NEW Component named P1
Click on P1 (on Palette)
Put P1 on Form
My God, it works!!!

One thing though:

When you create a COMPONENT TEMPLATE you get the graphic Components copied.
        and most Properties, and all the Event code of all the objects in the Template.
Experiment using Component Templates, to see how they work.  They are a great resource.

Note: I recommend placing all the components on a Panel, then making a COMPONENT TEMPLATE out of the Panel.

Anyway, this is a great way to build up a Library of groups of Components, that you can easily reuse;  its on your Palette.
Later I will create a Delphi Project with a lot of Panels that you can save as COMPONENT TEMPLATES.

 

COPYING A FORM TO THE REPOSITORY

Create a New Form, put on Buttons, Panels
Right Click on the Form
    -Select ADD TO REPOSITORY
        -Enter a TITLE (e.g. TEST1)
            -OK

Now goto Menu
    -File
        -New

-Forms(Tab)

You will see a Selection TEST1
Double Click on it

WOW!!!

Now you have a simple way to save entire Forms, and reuse them.

 

Remember Delphi is complicated because there are so many choices.
What I want these Lessons to give you, is a way to simplify your choices; knowing which ones are important and which are not.

When you look at the ObjectInspector for a Button, you will see 24 Properties. You normally only use or change, 4 or 5 of these Properties. But Delphi shows you 24. So, for the new programmer it's a little overwhelming.

When you're done with these Lessons, you should get a feel for the core (or essence or flavor) of Delphi.
Now, when you look at the ObjectInspector, you only see the Properties that have any meaning for you.

 

That's it for now.

I hope these Ramblings have given you a better understanding of how to use Delphi's power.
Have fun, and keep reading your Delphi books.

 

Lesson 2    More Delphi Stuff   by Frank Fortino

Hi again,

The more code examples that you read, the more you will see similarities and the common structure of Delphi Pascal.
When I first started reading Delphi code, I only knew what a few lines meant;  everything else didn't make sense. (e.g. (Sender : TObject) )
When You really learn Delphi, you will understand EVERY LINE of code.

 

OK Let's get started on More Delphi Stuff.

What is an OBJECT (Component)?

Remember a Component is an Object on your Palette
    -an Object, can be a Component on your Palette,
    -or something that is created totally in code

-So an OBJECT is a more general class of things, than a COMPONENT
-All Components are Objects
    -But Not All Objects are Components (TStringList is an Object, and Not a Component)

I sometimes slip and call Components Objects (and so do some other people).


 

-What is a PROPERTY?

-A Property is nothing more than a Variable (e.g. word, string,...) that has some built-in Methods (functions) to Read and Write to it's Variable.

COMMENT:
I sometimes use these words to mean the same thing (but they are different):
    -Procedure (a chunk of code that does something)
    -Function (a procedure that Returns a Value (e.g. Result:=1; )
    -Method (a proc. or function built into a Component)
    -Subroutine (a generic term, I think from BASIC)


 

-What is a METHOD?

-A Method is a function that is attached to an Object
  For Example:
      a ListBox (which can hold an array of strings) has a Method (Clear) that makes all the strings ='' in the ListBox.

CLEAR is a Method of the ListBox.

begin
  ListBox1.Clear; // Clears the ListBox
end;

Also, some Properties of a Component can have their own Methods
(e.g. Items, is a Property of ListBox)
    Items, is of type TStrings
    TStrings, has a Method 'LoadFromFile' that Opens, Reads and Closes a File

ListBox1.Items.LoadFromFile('c:\Data1.txt');

 


 

-What is an EVENT?

-An Event is a User Action (Mouse Click, KeyPressed,...)
    Events all begin with the word 'On'

--------------------------------
    OnClick ..                     Button1Click(Sender : TObject)
    OnKeyDown ..              Button1KeyDown(Sender : TObject)
    OnMouseMove ..          Button1MouseMove(Sender : TObject)

Events are where you write your Delphi code.


 

Using this TUTORIAL

    1) There is no overall order to the TOPICS
    2) Each TOPIC should stand on its own You don't have to read 2 pages ahead.


 

Simple Experiment to better understand Delphi (.dfm/Form):

-New Form (Form1)
-Add Button (Button1)
-Click on Form1
-Alt F12 (switches to Unit1.dfm - same as View As Text)

    Note: You can use Alt F12 to Toggle back and forth from (Form1 to Unit1.dfm)

What do you see?

    Unit1.dfm File (as a text file - which it is not)

object Form1: TForm1 // Here's the Form1 defined
  Left = 200
  Top = 108
  Width = 696
  Height = 480
  Caption = 'Form1'
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'MS Sans Serif'
  Font.Style = []
  PixelsPerInch = 96
  TextHeight = 13
  object Button1: TButton // Oh Here's Button1 defined (under Form1)
    Left = 220      // Form1 is the Parent(and Owner) of Button1
    Top = 120
    Width = 75
    Height = 25
    Caption = 'Button1'
    TabOrder = 0
  end
end

OK Now

    -Click on the Unit1.dfm text
    -Alt F12 (to see Form1 again - same as View As Form)

    -Add a Panel (Panel1)
    -In Object Inspector change Panel1's Color to RED

    -Click on Form1
    -Alt F12 (View As Text)

What do you see?

object Form1: TForm1
  Left = 200
  Top = 108
  Width = 696
  Height = 480
  Caption = 'Form1'
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'MS Sans Serif'
  Font.Style = []
  PixelsPerInch = 96
  TextHeight = 13
  object Button1: TButton
    Left = 220
    Top = 120
    Width = 75
    Height = 25
    Caption = 'Button1'
    TabOrder = 0
  end
  object Panel1: TPanel // Here's Panel 1 defined
    Left = 284
    Top = 204
    Width = 185
    Height = 41
    Caption = 'Panel1'
    Color = clRed    // YES the Color is RED
    TabOrder = 1
  end
end

 


 

Do you see what Delphi is doing.

As you add Components to Form1 and change Properties, Delphi is creating (pseudo) code (in Unit1.dfm) to define what you did.

Normally YOU DO NOT CHANGE the Unit1.dfm File;  You should only work on the Visual Form1.


 

And now for something completely different.

How does Delphi and your Delphi program work with Windows 95

(The following is not very technical, it is only trying to explain in simple terms, how things work)

What is Delphi?
-The Delphi (IDE) is a Visual Interface between You (the User) and your Computer (that is running Windows 95).

-Delphi translates the Visual Components (Buttons, Panels,..) on your Form (your Form is basically a Window to Win95);  into an interim (pseudo) language (in Unit1.dfm) that defines how to build the Form and Components; and also defines all the Properties of the Components.

When you Compile your program; What happens?
    -Delphi goes to the .dpr file (your project file)
    -Delphi asks - What Program Chunks are in the Project
    -.dpr file answers:

uses
  Forms,
  Unit1 in 'Unit1.pas' {Form1}; // Oh Unit1 and Form1


-Delphi asks - What do I do first
    -.dpr file answers:
-------------

begin
  Application.Initialize; // Initializes stuff
  Application.CreateForm(TForm1, Form1);   // Creates Form1
// using the Unit1.dfm file
  Application.Run;                       // Runs Program
end.

-------------

Now you are inside your Program, waiting for Events (User Actions) to be sent to you from Win95.

The MASTER (Win95) is running on your Computer, and every time the User Clicks the Mouse or Hits a Key; Win95 (by way of the Applications Interface (Win API)) sends your Program a Message.
    - Remember Application.ProcessMessages (from Lesson 1)

What 'Application.ProcessMessages' does, is it gives Control back to Win95, so that Win95 can Process Keys etc. and Display windows (your Form is a window)

Remember your Computer is only 1 Little Guy (Pentium...) trying to do multiple things at one time (MultiTasking).

What Tasks does Win95 do? (only some of the things it does):
    -Watches the Keyboard
    -Watches the Mouse
    -Draws Windows on your Monitor (Screen)
    -Runs your Program
    -Runs other programs

Win95 does MultiTasking by controlling your Computer;  and only Running each Task for a short period of time (say 50 msec) then switching to the next Task for (50 msec) then switching to the next Task ... finally getting back to the first Task.

So Win95 makes your Computer look like a Multiple number of programs are All Running at the same time.

BUT MULTIPLE PROGRAMS ARE NOT RUNNING AT THE SAME TIME!

It is just multiple Tasks being Run in a loop (by 1 guy).

That's why you must use 'Application.ProcessMessages' inside your Button Click Event. (as described in Lesson 1)

You have to relinquish Control back to Win95, in the middle of the Button Click procedure; so that Win95 can look for Key Hits and Draw your Form.


 

Setting up your PROJECT and ENVIRONMENT OPTIONS

    (following is the way that I have my Delphi 3 Pro IDE setup)

-Project(menu)
-Options
-Compiler(tab)

    Code gen.                                         Runtime ...
    X Aligned record...                             ALL CHECKED

    Syntax ...                                           Debugging ...
    X Stack -                                               ALL CHECKED
    X Extended -
    X Open -
    X Huge -                                            Messages
    X Assembler-                                     ALL CHECKED

----------------------

-Tools(menu)
-Environment Options
-Preferences

    X Desktop Only             X Editor files
    X Desktop

Form Designer                                  sizeX     4
  ALL CHECKED                                sizeY     4
 

    Debugging                                 Compiling ...
    X Integrated-                                 X Show-
    X Break -                                      X Minimize-
    X Hide-
--------------------------------------------------

-Library
    X Show Hints
    X Show Messages
--------------------------------------------------

-Code Insight
    X Code Completion
    X Code Params
    X Tool tip Expression Eval.

--------------------------------------------------

-Colors

Select Colors for:
    Comment (Red)
    Reserved word (Blue)
    String (Pink)


 

Delphi Inconsistencies:

1) .dpr and .pas Cannot have the same name. Why not?
        One file is SysSet.dpr
        and the other is SysSet.pas // Not Allowed

2) You CANNOT change the Color of a Button

Most Components allow you to change their Color, But Not a Button
Why Not?
Because (for some reason) Delphi does not draw the Button, it has Windows 95, draw the Button; so Windows uses the Default Button Color (in your Windows Setup).

3) Delphi (Depending where you are in Delphi) uses:
        -FLOAT, REAL, SINGLE, DOUBLE and NUMBER All for float type variables
        -CURRENCY and MONEY for currency type

4) Delphi's Help examples are shared for different topics,
    Probably to save space. It would help us learn more, if they had individual, simple examples.

For example: If you look up 'FORMAT FUNCTION' you get one tiny example; while Format has 8 different format types.
They should, show us an example that uses all 8 types.


 

Third Party Components

This is another resource you have to improve your Delphi POWER TOOLS.
I've downloaded hundreds of really neat stuff.

But if I look at my installed Components;  I don't see many that I use; that I didn't have to pay for.

This does not mean that you should not Download free Components.

You should Download anything that catches your eye.

Examples of where Free Components that can improve Delphi:
    -Colored Buttons
    -Improved DBGrids (that auto-link to LookupComboBoxes)
    -Database stuff
    -RS232 Serial Component
    -...

The best sites that I have found, and use all the time:

    DELPHI SUPER PAGE
        http://sunsite.icm.edu.pl/delphi/

    TORRY"S DELPHI PAGES
        http://www.torry.ru/index.htm is.

Both have Components sorted by Category.

As a note, I use 2 Components that I think are worth the money (<$100)
and they have their own newsgroup, for great support:
  ACE Reporter (Report Program)    http://www.sct-associates.com
      replacing QuickReport that has too many problems
  Youseful (Installation Program)        http://www.youseful.com
      replacing InstallShield that also does not run reliably


 

Installing New Components

This is more complicated than it should be.

First you Should Create a New Package
    All Components go into Packages

You DON'T want to Install New Components in the Packages that Borland gives use (at least not normally).

You do not want to corrupt the installed Delphi Packages.

To Create a New Package you have to Install a New Component into it.
    (we should be able to just create a Package, before we add Components, but we can't)

Creating a New Package (and Installing a Component)
    -Component(Menu)
        -Install Component
            -Into New Package(Tab)
                -Enter Name PACKAGE FILE NAME e.g. 'Test1'
                -Browser(Button)
                    -Pick .pas or .dcu File (for the New Component)
                            (that you Downloaded from the Web)
                -Open
                -OK
                -hit OK ...
                -Exit (X on top right of Dialog Box (Dialog Form)

Note: You can Install a Component from a .pas or a .dcu
If you only have a .dcu (built by Delphi3), D4 will not Install it. If you have the .pas then, D4 can install it.


 

Installing a New Component in an Existing Package:
    -Component(menu)
    -Install Component
    -Select PACKAGE NAME FILE (e.g. 'Test1')
    -Browse (for UNIT FILE NAME) (as .pas or .dcu)
    -Pick a file
    -Open
    -OK
    -Confirm YES
--------------

Later I will show you how to Uninstall a Component.
It is a little weird.  I have to investigate it further.


 

Another Topic:

I looked at some other free Delphi Tutorials; GEEZE! They either don't say much, and don't cover much territory; or they are too detailed, and go so slow.

When I was trying to learn Delphi, I got little or no help from them.

Anyway, I am going to cover a lot of turf, trying to give you some good advice
    (and also some of my (sometimes not mainstream) design Principles).

Hopefully when I am all done, I will have given you:
    -A list of DO's and DON'Ts
    -A programming Philosophy (Style and Principles)
    -A Library of Important stuff
    -An Overview of how Delphi works
    -Some good Power Tools for you to learn on your own
    -Some good examples
    -And places to go to get Help

I want to show you how to make your own examples and learn new things.

Like TEACHING YOU TO FISH rather than GIVING YOU FISH.
    (gosh, is he quoting from the Bible???)

Remember use your books, use the Index and Table of Contents to find all the nitty-gritty details of topics that I expose you to.

These Lessons should not read like a book, all organized with lots of details. You have books for that.

What I want to give you, is another way of seeing Delphi, sometimes looking from above; and sometimes in the inner bowels of Delphi.


 

QUIZ

Q1) When you start a New Project what is the first thing you should do?

    Tick, Tick, ... BEEP Times Up

    YES, you should Rename the Form, Unit and Project and save them in their own unique Folder.

Q2) When you put a Button on the Form, what should you do first?

    YES, Rename the Button (e.g. ReadBtn)

Q3) What is SENDER?

    Answer - It's a parameter(a variable passed to a procedure)
        (used by a Delphi Event)

    -What type is it?

        Ans. - It's a TObject (YES)

Wait, it's a TObject; EVERYTHING is a TObject; So What?
That doesn't tell us much.

-Why is it a type TObject?

    Ans. - So that it can be any kind of Component (Button, ListBox, Edit , ...)

OOOOh, I see, it's a general type (TObject) that lets it be assigned to ANY type of Component.

YES, YES

---------------
This is fun. I like talking to myself.
---------------

Q4) How do you make a Copy of a Form (explain all the ways)?

    -Copying Forms

            1) Use Win Explorer to copy .pas .dfm Files     (YES)
            2) Add Form to Repository (see Lesson 1)     (YES)
            3) Open the ProjectMgr(Toolbar)
                    -Select ADD
                    -Pick .pas file
                    -A copy of the Form is Added to Project (WRONG)

                The Unit and Form get added to the Project, but NO COPY is made of the original Unit & Form,
                so any changes you make, will change the Original Form.

                Nothing is copied Unless you do:
                    -File(menu)
                    -Save As (new file name)


 

Franks Programming Philosophy 101

    1) First Make it Work
            Then Make it Pretty
                -Organize
                -Minimize

    2) You can write code (build a project) in 15 minutes, then it takes you 2 hours to make it work right (debug).

So, what is the most important thing to keep in mind when you write a program?

YES - MAKE IT EASY TO DEBUG (and MAINTAIN)

How, do you make it easier to Debug - you say?

    Step 1) Write Inline code first, don't worry about creating subroutines (procedure) calls for redundant code.

    Step 2) Name things consistantly and compactly, but use names that document what you are doing.

    Step 3) Test your program
                    (remember Murphy's Law: If it can go wrong it will go wrong)

    Step 4) Use every way you know, to make your code easily readable; even use Global variables.

I don't believe it.   Did he say use Globals.  Oh No.

COMMENT:

    Today's Headline 'GLOBALS - Heaven or Hell'

    The Great Unknown.

    Most people do not know how to use Globals CORRECTLY.
    They are told to totally avoid them.

    There are times when it IS appropriate to use Globals.
            -When it makes your code easier to read and maintain.

    Most people don't have the foggiest idea of WHEN and HOW to use them.

With Global Variables you can:
    -Have Access to ALL variables from ANYWHERE (in all your Forms(Units))
    -Call Procedures without passing Parameters(passing data) or with a minimal number of params

Bad things (difficulties) with Globals
    -Someone else can change your data in a multi-programmer project
    -A Unit does not stand on its own, if it uses Globals defined in another Unit.

Rules for Using Global Variables:
    1) Use them sparingly
    2) Keep track of them
            -Keep Them in One Place
            -Assign them in 1 place; Main or common Unit
                    e.g. (in Main.pas)
    3) Name them with a X starting char, or some other unique way
            So that they STAND OUT.

XFileName : string;
XCountyStr : string[32];
XDate : TDate;
XCnts : array[0..255] of byte;


Where do you put Global declarations?

    Ans:  In the interface section:

var
  Form1: TForm1;
  XFileName : string[64];      // Global
  XDate : TDate;               // Global

implementation

In later Lessons, I'll have some sample programs that show you how to define and use Globals.


 

COMMENT:

    Everything that I tell you is not always totally correct, but it's close enough.
    To get the real scoop; look things up in Delphi's Help(F1) and Books.

    These Lessons are just to expose you to stuff; and sometimes to look at things from a different angle

    But remember; in Delphi, sometimes it's very hard to go backwards, so try to be consistent.

    Also, don't do all your programming on the Computer.
    I still use a pencil and paper (A Lot).

    And, Clean up your code as you go.


 

Delphi Insights that I have had in my learning experiences
    (not in any specific order)

I will go into some of these in detail in future Lessons.


 

This format is fun, I always loved teaching.  I only taught Elect. Engrg in College for 2 years.

I always hated homework; and teaching had tons of homework;  and the pay sucked.

By the way; I cannot answer many of your individual questions (for now). I really have a lot to tell you, in a short time;  so I can't do things on an individual basis, yet.

But, still send me your comments and questions; since I want to learn more too.  And make these Lessons better for future readers.

Here's how you can help me and others. And that's the whole idea. These Lessons are pretty crude right now, so I could use some help cleaning them up, improving them, adding to them and organizing things better.

So any help would be greatly appreciated.


 

When you create simple example programs for yourself; (when you want to better understand a new Component etc.)
Save them, and later we might be able to use them (give them to others) as part of this Tutorial.


 

Looking at how the style of these Lessons has evolved:
    -free form
    -changing Topic instantly
    -when something new comes up (explain it right there)

Books are different; they are Super organized
    -They are great: as a reference, and for details
    -They are difficult: when you are first learning and are overwhelmed by a lot of new stuff.

So maybe this is a different way of learning.


 

If you have anything that you think would help others; please send it to me, so that we can all use it.
That way we can all learn together (more quickly).


 

BACK TO DELPHI

Using Breakpoints to see how Delphi works:

A lot of programmers seldom use BreakPoints(B.P.), or they just use them if they have a coding problem. They are missing another great feature of BreakPoints; to see how Delphi works, and see the sequencing of how your code runs.

Breakpoints:

    -New Form
    -Add Button1
    -Dbl Click Button1
    -Add the following code (in Button1's OnClick Event)

procedure TForm1.Button1Click(Sender: TObject);
var x,y : word;
    s : string;
begin
  s:='15';
  x:=StrToInt(s);
  x:=x+1;
end;


    -Compile(Build All)

-You should see little Blue dots on the left of each line(in Unit1.pas) that you can put a Breakpoint on.

-Click on the Blue dot on line:
    x:=StrToInt(s);

-The line should now be highlighted in RED
    This means that you added a Breakpoint (B.P.) there.

-Click the RED dot (the Blue dot also turned Red)
    The Breakpoint should go away  The dot is Blue again

-Click on the Blue dot again
    This sets the Breakpoint again

-Now Run the Program and Click Button1
-the Program stops on the line with the B.P.
-Also a little Green Arrow appears by the line;
    this tells you that the Program is here  (and IT HAS NOT RUN THIS LINE YET)

Now there are 3 important Keys to use:
(DON'T HIT THESE KEYS YET)

    F8 will Single Step, and only run 1 line of code.

    F9 will Run the Program until it hits another B.P.
        If there is no other B.P., then the Program just runs normally.

Ctrl F2 will Reset (Stop) your program

-With the program stopped on your B.P.

-Just move the cursor over the Variable 's'
    What happens?

A hint pops up with  s='15'
What is going on?

Delphi lets you see the Value of all your Vars;  by simple putting the cursor over the Variable.

Touch 'x' (put the cursor over it)
    It should say   x=3462     // or some random number

Why does     x=3462     and not     x=0?



IMPORTANT POINT

 

    Delphi Automatically Initializes every Global Variable before the Program runs.
    Integers are 0     x=0
    String are null     s=''
    arrays are ALL nulls or 0's

    So, you NEVER have to Initialize a Global Variable to 0 or NULL

    Local variables are NOT initialized.  And x is a Local var.



OK

 

-Now hit F8
    -and the Green Arrow moves to the next line

Touch x
    -should show     x=15     (in a hint window)

Now STOP YOUR PROGRAM
    -How do you Stop the Program?
       Ans: Hit Ctrl F2
                or -Run(Menu)
                        -Program Reset

Stops your Program, and puts you back in the Delphi Editor

Now, run the Program again (Hit F9)

-Click Button1 again

And play around with F8, F9 and touching Variables.
    Until you understand what's happening.

You should use Breakpoints, to go inside your code a lot.
    That's how you learn how Delphi works.

Later I will cover Breakpoints and Debugging Techniques in detail, but this is good enough for now.

Write more code, and add Breakpoints.

THIS IS ONE OF THOSE INSIGHTFUL TIMES
    At least it was for me, when I first discovered how elegantly Delphi handles Breakpoints.


 

Frank's Philosophy

    It's a lot easier to write complicated code.
    It takes a lot more understanding to simplify the problem down to it's ESSENCE.

    There is genius (and a lot of hard work) in an Elegant, Simple design.
    Thank you Delphi.

    One thing to avoid; Do Not get to tricky or compact your code too much.
    Remember you want your code to be easy to read and understand.

Which is easier to read: (A or B?)

A                                                     B
-------------------------         --------------------

xxxxxxxxxxxxx                         xxxxxxxxxxx
xxxxxxxxx                                xxxxxx
xxxxxxxxxxxxx                         xxxxxxxxxxxxxxxx
xxxxxxx
xxxxxxxxxxxxxxx                     xxxxxxxxxxxx
xxxxxxxxxxx                            xxxxxxxx
xxxxxxxxxxxxx                        xxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxx                       xxx
xxxxxxxx
xxxxxxxxxxx                            xxxxx
xxxxxxxx                                 xxxxxxxxxx

I think B is easier to read (it has more structure)

You should use blank lines to put your code into functional blocks.

That's it for Now.

Frank

Lesson 3     Databases    by Frank Fortino    

Download Lesson 3 examples here

     These Lessons will continue to jump around from Basic Concepts, Comments, Power Tips, Warnings, ... so that both experienced programmers and raw beginners, will be able to read them, and find something that can help them.

I've included 14 Example Programs for you to Learn From in the L3Examples.zip file.  Try running and Modifying them ALL.

I could not cover all of Databases in this Lesson, so I will have another Database Lesson

I will have more Lessons on Databases (Covering SQL (in detail), ...); with lots of examples.
So, for all the really new Delphi programmers, you might not understand everything, but you should read and do this Lesson even if you do not understand things yet.

Remember, this is a beginning Tutorial, so I can only cover the basics of Databases.
To get more in depth information, read up on Databases in your book(s).


 

When I was doing Turbo Pascal programming in the early 1990's, I avoided Database programming because it was a whole new complicated language to learn (either DBase3 or Fox Pro).

So, when I found out that Delphi handled databases, I thought it would be the same complicated structure.
But to my surprise, Delphi did something different. They simplified and organized everything about Databases so well; that now I use Databases for everything.


 

I am only going to cover Local Paradox Databases, and Local SQL.  You should have received LocalSQL.htm with Lesson 2.
    Email me if you need a copy of LocalSQL.htm

Some parts of Database programming are hard to explain in words, so I have created a few simple example programs; for you to play with Databases, and learn how to use them.


 

Note:

This Lesson is not organized very well yet. Databases are really very complicated critters. They include an lot of inter-related parts and features.
I cannot explain all the interaction here; first, because I don't know everything about Databases, and secondly it would be too detailed (like a book again).

So, I am going to jump around a lot. But don't worry, just keep on reading and some of what I say will make sense later. I want you to immediately start using Databases.
Don't just read about them. And I also want you to use SQL, right from the start.

So, ALL ABOARD, let's get this train moving.


 

What is a Database(DB)?         Note: In some places I use DB for Database (for brevity)

Let's step back and look at Databases a little differently.

First let's define all the new terms:

-Database
-Table
-Record
-Field
-Query
-Dataset
-SQL
-Datasource
-Persistent
-Key
-Index
-Secondary Index
-Cursor
-Calculated Field
-Lookup Field
-Database Types:
-Programs and Tools that manage Databases:
-Local Database
-Alias
-Data Aware Components
-DBI


 

- Database = A collection of Tables.

- Table = A collection of Records, made up of one or more Fields.
                      Files on your Disk (.db .px)

- Field =  A column in a table. Stores one and only one piece of data.

- Record = A logical collection of fields in a table, often referred to as a "row"

-Query = Like a Table, but uses SQL statements (string statements) to Read and Write data to the DB

-Dataset = Refers to a Table or Query

-SQL = Structured Query Language; a great search and sort set of functions for DB's

-Datasource = The Link (to the DB) for Data Aware Components like  DBGrid, DBEdit, DBLookUpComboBox, ...

-Persistent = Refers to Real Fields that exist in the DB File, rather than Fields that only exist in Memory, not in the DB on Disk
        (Calculated and Lookup Fields are NOT Persistent)

-Key = The Primary Index (the Field(s) used to sort the Records of the DB)

-Index = The Field(s) used to sort the Records of the DB (can be Primary or Secondary)

-Secondary Index =Another Field('s) used to sort the Records of the DB

-Cursor = The Record pointer (to the 1 Record in the DB that you can Read and Write to)

-Calculated Field = A Field that you calculate from real (Persistent) Fields of the DB
        Calculated Fields only exist in Memory and are Not Persistent

-Lookup Field = A Field looked up in another DB, using a Key Field (in both DB's as the reference).
        A Lookup Field is Not Persistent

-Database Types:
        -Paradox =A Database format (how data is stored on disk) (Which I use)
        -DBase =An older Database format (which I do not use)
        -Access,  other DB's

-Programs and Tools that manage Databases:
        -BDE The main program that does all the DB work
                (its a DLL (Dynamic Link Library) that you must install with your .exe file (using Install Shield Express))

        -DataBase Desktop A Tool (program) that lets you Create DB's from scratch, and View and Edit DB's.

        -BDEcfg32 =A program that lets you create Aliases

        -Database Explorer  (I don't use it much)

        -Local Database = A DB that exists on your computers Disk, and not on a Server

-Alias =The Path (Directory) of the DB (on your disk)

-Data Aware Components
        -DBGrid
        -DBEdit
        -DBLookUpComboBox
        - others (I will cover later) Their names start with DB...

-DBI = Calls to the BDE, like Windows API calls
        (I try to avoid using them, because they have tons of parameters)


 

Q: What are the minimum Components it takes to use a DB?
        Ans.   2    a Table and a DataSource    (or a Query and a DataSource)


 

COMMENT:     Why 2 things, why not just 1?   (I don't know that answer)
        Here's what I do know:

            -When you want to Read or Write data (a Record) to the DB, you use the Table

                    e.g. Table1.FieldByName('CustName').AsString:='Bill Thomas';

            -All Data Aware Comps (DBGrid, etc. ...) use the DataSource to Link themselves to the DB


 

What are the minimum steps it takes to use a DB?          (checkout the   FirstDB.dpr   program)
        -Put a Table on the Form (Table1)
        -Set Table1's Properties (in ObjectInspector)
                1) Table1.DataBaseName => 'DBDemos' (the ALIAS Folder path that has the DB file)
                        -Delphi picked a strange name for this Property
                        -DataBaseName Should be called DataBasePath, or DataBaseAlias BUT IT IS NOT
                2) Table1.TableName => 'Customer.db';
        -Put a Datasource on the Form (DataSource1)
                -Set DataSource1.DataSet => Table1


 

NOTE: To show you a selection in the ObjectInspector I will use '=>'
                            In code use ':='

        I will use this Format throughout these Lessons


 

Some Confusing things about Databases:

    -DatabaseName (a Table Property), Alias and (the path to the Folder with the DB files) all mean the same thing.
    -A Table has a Property called 'DatabaseName'
            -which specifies where the Database file (on disk) is located.
            -It is basically the path of the Folder with the DB:
                    e.g. c:\D3Data\DBases
            (The DatabaseName Property should be called DatabasePath; but it is not)


 

Notes:
        -I use the words Directory and Folder to mean the same thing.
        -I will use OBJI for ObjectInspector


 

You could run the BDEcfg32.exe program and specify an Alias for the path: (Which I will not explain here)
        e.g. MyDataBases = c:\D3Data\DBases
                        MyDataBases is an Alias

If you defined an Alias (using BDEcfg32.exe) then that Alias will appear in a pick list for the Table's DatabaseName Property (in the OBJI).

If you do not enter anything for the Table's DatabaseName Property (in the OBJI), then you (by default) have picked your current directory (folder) to be where the Database files are located.

If this seems a little confusing, it will become clearer when we play with our example program (FirstDBP.dpr)

So, for now, just realize that the DatabaseName Property (of a Table) is just a path (pointing to a directory).


 

3 ways to organize your Databases
        1) Put the DB (.db .px files) in your current Folder
                Then you do not have to specify a Table1.DatabaseName (in the OBJI)
             // This is what I use when I am first developing a program, so the database stays with each
                version of the program.  This helps when I add new fields, or change field definitions.

       2) Put all your DB files in a common Folder (e.g. c:\DB\Data)
                Then specify Table1.DatabaseName(as a Path) => 'c:\DB\Data' (in the OBJI)     // This is what I use most

        3) Put all your DB files in a common Folder (e.g. c:\DB\Data)
                Then create an Alias with BDEcfg32


 

Frank's preference:
    I do not like using Aliases. They require me to run BDEcfg32.exe to specify the Alias.
    And when I install the final program on a different computer, I have to setup the Alias on that computer.
    So, I put all my Databases in 1 Folder
    And then I specify the path in the Table1.DatabaseName Prop.
        e.g. Table1.DatabaseName => 'c:\DB\Data'


 

So, what's so great about a Database?

Well, Databases are automatically Sorted, Filtered and Searched with a whole array of powerful Methods and functions.
        e.g. Table1.Filter:='CustNun>1000';
        Table1.Locate(..)     can locate(find) matching fields and sub-fields

Also, there is this thing called SQL  that does some Fantastic stuff. I will talk more about SQL later (and in later Lessons)
It's such a important and powerful feature of Databases.

You never have to manage the DB file, it is all done in the background by the BDE (Borland Database Engine).


 

COMMENT:

You cannot copy an entire record with 1 command.
What? I thought that DB's were powerful.

A Table only gives you access to 1 record at a time; and you cannot easily make a copy of a record. (you really can but it is complicated, so I won't discuss that here)

You have very easy access the Record's Fields. So you copy a Record by copying all its Fields.

This is one of the few weaknesses that I have found with Delphi's Database structure.


 

There are multiple ways to access (read/write) a Field:

    Table1.Fields[3].Value:='Frank'; // .Fields is an array

    Table1['CustName']:='Frank';

    Table1.FieldValues['CustName']:='Frank';

    Table1CustName.AsString:='Frank';
                    (if you ran the Fields Editor and selected the CustName Field)

    Table1.FieldByName('CustName').AsString:='Frank';
                    (this is what I normally use)

Wow, this is getting a little crazy. Why all the different formats?
Run Example Program:     DBReadField.dpr


 

Calculated Fields:

Calculated Fields are only for display purposes only,
They are not Real (Persistent) Fields in the .db File; they only exist in Memory.

You CANNOT Search or Sort on Calculated Fields.
So, be aware that Calc. Fields are not real.

To use a Calculated Field, you have to do 2 things
        -Create a New field for a Table using the Fields Editor
                (Right Click on Table and select Fields Editor - then read your book on how to add a Calculated Field to a Table)
        -Use the Table's OnCalcFields Event, to do the calculation and put the data in the Calc. Field
                e.g.
        n1:=T1.FieldByName('N1').AsInteger;         // N1 and N2 are Real Fields
        n2:=T1.FieldByName('N2').AsInteger;
        T1.FieldByName('CalcN3').AsInteger:=n1+n2; // CalcN3 is a Calculated Field


 

Database WATCH OUTS

-DO NOT set a Table's Active Prop. => True in the OBJI (when you create the program)
        You should Open the Table in the Form's OnShow Event
        begin
          Table1.Open;
        end;
-DO NOT try and change any Real (persistent) Field of a Table from the OnCalc Event (of the Table)
        You can only change Calculated Fields in the OnCalc Event.
        If you try to change a Real Field, the OnCalc Event is called again (putting you into a recursive (endless) loop BUMMER)


 

Searching a Database

Delphi has multiple Methods to search for data in a Database
    -Find
    -FindNearest
    -GotoKey
    -GotoNearest
    -Lookup
    -Locate
    -SQL

    I very seldom use Find, FindNearest, GotoKey, GotoNearest or Lookup.
    They all require the DB to have an Index for the Field you are searching for a match.
    If you have a lot of different fields you want to search on; then you have to have a lot of Indexes (usually secondary Indexes)
            with each secondary Index requiring 2 extra files.

    i.e.

        Indexes         File Cnt         Files
        -------             ----------          ---------------------------------
            0                     1                     .dpr
            1                     2                     .dpr     .px
            2                     4                     .dpr     .px     .xg0     .yg0
            3                     6                     .dpr     .px     .xg0     .yg0     .xg1     .yg1

        So for 3 Indexes (1 Primary and 2 Secondary) you have 6 files .
                That's a lot of Files for each DB that you have.

    I useTable1. Locate() when I want to move the Cursor (pointer in the Table) to the found record. This is handy with the loPartialKey param that will find partial matches, for example as the user types, the grid moves to the nearest match.
        Table1.Locate('CustName', 'Frank Fortino', [loPartialKey]);

Run Example Program:     FilterLocate.dpr


 

Letting the User See and Touch a Database

The only way the user can see and touch a Database is with the Data Aware Comps.
        -DBGrid, DBEdit, DBLookupComboBox, ...

The DBGrid is the Big Kahuna (most powerful) of the Data Aware Comps.

-New Application

-Put a Table1 on Form1     DatabaseName => DBDemos     TableName => Employee.db
-Put a DataSource on Form1     Dataset =>Table1
-Put a DBGrid on Form1    DataSource => DataSource1

-Point to Table1   Set  Active => True
        the DBGrid should now display the Employee.db Database

-Point to Table1   Set  Active => False

In the FormShow Event set Table1.Open
    procedure TForm1.FormShow(Sender: TObject);
    begin
      Table1.Open;
    end;


 

A Franky Technique:
    -Use DBGrids to display data only, Not to Edit data
    -Why? Because they are too powerful, and have too many features that can create some real nasty problems. I will explain these problems in some examples later.
    -Use a group of DBEdit boxes to Edit and Change data; and these sometimes have they're own Datasource and Table (using the same Database on disk).


 

SQL

select
from
where
order by

    Basic SQL Structure
        'select A,B from C where D>10 order by E'
                            -A and B are the Fields you want in your Record
                                    e.g. select CustName, CustNum from ...

                               Note: an * selects All the Fields in the DB
                                            e.g. select * from ...

                            -C is the Database name
                                    e.g. select * from Customers.db

                            -D is a Field that you want to Filter data on
                                    e.g. select * from Customers.db where CustNum>100 ...

                            -E is the Field that you want to sort data on
                                    e.g. select * from Customers.db where CustNum>100 order by CustName

    With SQL you can do MARVELOUS things


 

WARNING:
    You have to be very very specific in the way that you write your SQL statements.  There is no margin for error.
    Quotes (" and ') have to be used correctly
    Any names that you use that match SQL's reserved words, must be put inside Quotes.
        e.g. select "Index" from Parts.db     Your Field named Index matches SQL's reserved word (Index)


 

Lets write a ButtonClick Event that does some SQL

     Q1 : TQuery;

procedure TForm1.SQLBtnClick(Sender: TObject);
begin
  Q1.Close;
  Q1.SQL.Clear;
  XStr:='select * from Customer.db where CustNo>1000';
  Q1.SQL.Add(XStr);
  Q1.Open;
end;

 


 

Frank's preferences:

    I do not use Parameters in SQL, they are a little cryptic in their structure, and I haven't found a need for them.
    So, I build all my SQL's up as a strings, as shown above.


 

Well that's about it for now.

Frank



 
 
 

Lesson 4      Delphi   by Frank Fortino    


Hi again,

 

Let me state again, that these are only my opinions and things that have worked for me.  Other opinions are welcomed.

Some people have emailed me back:
 - catching some errors
 - explaining things I didn't know
 - showing me other programming styles and techniques

So I am continually doing minor updating.  But nothing major has happened to Lesson 1,2 3 yet.


 

I have found that it is harder to create these Lessons as I get into more detail.

What help is available to the Delphi programmer now:
1) Other web sites with Components, Tips and Tricks, Code snippets etc.  A great resource that everyone should use.
2) Borland Newsgroups.  Great for specific questions, and for help you cannot get anywhere else.
        This is where the Delphi experts, freely give advice.
        It is not very good place for the real newcomer to learn the basics of Delphi, since most of the answers are kept very concise.
        Every good Delphi programmer should read the messages on a few of these newsgroups.
            It's a great way to learn some specific solutions from Delphi experts.  I use them all the time.
3) Books   There are a number of excellent books, on every part of Delphi.  Buy as many books as you can afford.
4) Web Tutorials  There are some new ones.

What help is missing:
1) Lots of simple, self documented Example Programs.
2) Good Reference documents that concisely show everything about a topic, on 1 or 2 printed pages
3) Good MidWare chunks, groups of Components that are well designed, visually pleasing and easy to use.
4) Good well thought out and structured Libraries of code snippets that cover most topics, and can be quickly retrieved
5) Examples of good programming STYLE, the Art of programming
6) Good Libraries of Macros -  Keyboard (Code) Templates, Component Templates, etc.

So, how do I keep these Lessons useful to the newcomer and also useful to the non-expert Delphi programmer?
Well, I decided to keep the Lesson part of this Tutorial more on the Overview side of things.  Trying to look at Delphi from different perspectives, and maybe giving some insights of Why and When rather than just How to do something.

I am coming from the small user side of Delphi; not the Enterprise, MIDAS, CORBA or whatever side.
There will be a lot more Delphi jobs, working for smaller companies than there are in large companies.  Sorry to say, that large companies usually play it safe, picking Microsoft (VB or VC++) over Borland products.  An employee for a large company can never be blamed for choosing software from the biggest guy on the block (MS).  But if he picks Delphi, now he could possibly be at risk.  So, he picks VB over the superior Delphi.
End of Report.

It is actually safer to deal with a smaller company.  A smaller company will try harder, and make the product work; otherwise they go out of business.  A large company, can sometimes simply drop (or stop developing) a product because it isn't a good enough profit center.
I hope Borland stays in tune with the smaller user;  where Microsoft is Not the safe choice.

Plus, an advantage of working for a smaller company, is that you can learn a lot more; by having to do everything yourself; rather than working on a small part of a large program.

There will always be a need for the genius programmers who can create a language like Delphi.  But there is a lot greater need for programmers, who can use Delphi, VB or whatever other super tools there are.  For every 1 job there is for a super programmer to develop a new component or programming tool, there are 1000 jobs for programmers to create User applications, Databases, build Web sites, do multimedia work etc.

So, get closer to the User side of programming, if you want to be able to do more, and have more job security.  Learn how to write HTML, Java Script, Java; besides Delphi.  Learn how to use multimedia stuff etc.  By the way, you can download free Demo software from a lot of sites. They are great learning tools.

Delphi is the language for everyone, not just expert programmers.  I have another Delphi programming example that I give people.
What if you wanted to write a program to drive a car.  Some people would write a complicated program that would have to know all the streets and stop signs, so that it could automatically drive the car from point to point.  All I would want, is a program to give me a Steering Wheel, an Accelerator and Brakes; then I can drive the car anywhere.  Delphi is that program.

For every 1 hour you spend writing code, you will spend 10 hours debugging and maintaining it.  So, make your code easy to read and understand First; then try to compact it and make it more efficient.  Gone are the days when you worried about how much RAM you use, or how many clock cycles it takes.  There are very few places where that is important anymore.  Sometimes I feel programmers get too deeply into the the nuts and bolts of programming, rather than how to make programs that work and are easily modified and maintained.  In school your taught to write recursive programs, sort routines and working with linked lists.  That is great to know; but, I feel that it is more important, to learn how to use programming tools rather then just writing programming tools.  One person creates a new tool once, then thousands of programmers use that tool thousands of times.  So, what is more important?  Yes, learn how to use the tools, the right way.  Of course my programming superstars are Cantu, Calvert etc.  But there are just a handful of them, and just a handful of jobs for them.  You can stand on their shoulders, just buy their books.  After trying to write these Lessons, I totally admire their book writing efforts.

Also, take a look at Visual Basic or Visual C++, then you will see why Delphi is different. You don't have to have an MS in Computer Science to be an excellent programmer.  Good Programming is very much an Art, and not just a coding exercise.  Some of the so called best programmers, can write the hardest to understand and maintain programs.  I call that poor programming.  Don't always try to use the trickiest and most complicated features. Try and use the best technique to make things easy to understand.  The idea is to make a program that anyone can read and understand and improve. Put your ego in your pocket.  The idea is not to impress others.  You really don't need the appraisal of others, to know that you have done a good job. With Delphi, programming style is ultra important; since there are so many different ways to do the same thing.  It is easy to clutter a screen up with too much color, or fail to organize elements is a simple and easy to understand way.  That's where the Art comes in.  What everyone needs, is examples of good style and function.  But where do you go to learn these things?

One last point.  The most important part of any project is the initial design and specification phase.  You should spend 40% of your time (not 10%), seeing what all your options are and deciding on a path to take.  Once you start on a path, it is very difficult to turn back.  So, be sure where you are going, before you start.

Also, you learn along the way; seeing better techniques as you build and try what you've done.  Remember, make it work First, then polish it.  Program Top Down, and Bottom Up. i.e. Do the overall design and program flow, and also start writing the primitive functions.  Then they meet somewhere in the middle.  And always expect to make changes.  What sounds like a good idea, sometimes isn't.

Here's another learning tip (that helped me in college).  When you want to learn something new, load data into all of you senses.  Look at it, say it out loud (hear it), write it down (or type it in).  Then it will stick better.  Your memory has a easy time storing data; the hard part, is to find the link to access the memory.

That's why you learn so much by physically doing something, rather then just silently reading about it.  It impacts your senses a lot more when you see, say, hear and feel it.  Also, there is a very generic truth in the saying "You learn more by your mistakes".  That is because making a mistake impacts you more.  You are frustrated, humbled and kicked all at the same time.  How could you ever forget that.
The worst thing to do is stand still, then you are sure to go nowhere. So keep on Trucking!  And that means, driving the Delphi truck.


 

Interesting Perception:

Franky likes to use Global Variables a lot.

New awareness:
  Your Global Variables are a Gigantic Global Parameter List that has a fixed structure
        (without needing you to remember the order of the data).

Question?  Do you see many Functions written with more than 6 Parameters?   Why Not?
     Because it would be hard to remember the order of the Parameters.
        and you have to pass ALL 6 Parameters (in the correct order),
        everytime that you call the Function.
    What a drag,  and also a chance for error.

Now, do you know why I dislike Parameters so much.
It's like using Reverse Polish Notation, or MODULO 2 (whatever that awful language was called)
It used the Stack to hold data, so the order of the data on the Stack had to be known.
What a total pain in the ass that was.  It's hard enough remembering the variables that you use,
    now you also have to know the order to pass them, and you have to pass them all, all the time.

With Global Vars you only have to change the vars that have changed, all the other vars that haven't
changed, are available, everywhere in the program.
This makes Debugging a lot easier, when you can see All the variables, whenever you need to.

Remember a good programmer will spend 8 hours Debugging and Testing his program, for each 1 hour of coding.
So, Debugging and Testing and Code Maintenance, should be number 1 on your list.

Compact Code with the minimum number of statements (is now a BAD HABIT)
Write your code to make it easier to understand.

For example:
var Prn, Int, Res: currency
begin
  Prn:=Q1.FieldByName('PrinAmt').AsCurrency;
  Int:=Q1.FieldByName('IntAmt').AsCurrency;
  Res:=Prin+Int;
  Q1.FieldByName('ResultAmt').AsCurrency:=Res;
end;

I think the above code is easier to read then the following code:

begin
  Q1.FieldByName('ResultAmt').AsCurrency:=Q1.FieldByName('PrinAmt').AsCurrency
     -Q1.FieldByName('IntAmt').AsCurrency;
end;

So, I like to use Local Vars to make my code easier to read.

 


 

Franky's Style:

Another thing that I do differently.

Q: Frank, why don't you use Data Modules?
Ans: I think that they are a little limiting, so I use a normal Form and Unit for a Data Module.

Yep, I do not use Data Modules.
I always use a Form (and Unit) for my Database stuff (Tables, Querys)
I usually name the Unit (DB1.pas) and the Form (DB1F)

I then put DBGrids on the Form (DB1F)  for each one of my Tables and Querys (with a DBNav for Editing each DB)
  (note: If I have a lot of Tables, I use a Tabbed PageControl, for multiple pages of DBGrids.)

Now when the Program is Running:
    I can then have a Button to call  DB1F.Show, to show the DB's when the program is running.

Now during Program Development:
   I can go to the DB1F Form, and make any Table Active,
   so that I can see the contents of the DB, and the Field Names etc.,
   and I can also Add New Records or Edit Records etc.

Another great Debugging Aid.
  Being able to see and manipulate all of your DB's, in the IDE environment, and when the program is running.

 


 

Let me vent a little bit:

  Q: Frank, what is your view of  the Window's Help *.hlp format and Menus?
  Ans:   It Sucks!

  Q: What do you like about *.hlp files?
   Ans:   Not very much, they Suck

  Q: Well, what do you like about Menus (Tree structures)?
  Ans:    They usually Suck?

  Q: Are we a little testy today?
  Ans:     No.  Just a lot of stuff Sucks.

Please God, stop me before I hurt myself.

There is one thing that I do like about *.hlp files
  The INDEX mode (search mode)
  Not the CONTENTS view    It S---s     Frank,  Stop that!


 

What is good User Interface Programming Style?

What do you think of Microsoft's standard Menu Structures?
  I would give it a C-.  Good job Frank, you refrained from saying the S word.

I strongly dislike Sub Menus.  If you have a Menu bar, use it more efficiently.  Put as much as you can on each Level (within reason)
Don't have 3 items on each Level, making me go 3 levels down to find what I want.

A Menu Tree structure can have some severe limitations:
  - Only 1 path to each object
  - Too many decision points
  - No easy access to secondary grouping of objects
  - No easy way to see all the objects in a sequential file (e.g. Print the tree)
     Try printing a *.hlp file, and you sometimes get 60 sheets with 4 sentences per sheet
     Yea, what a great structure.

If a Sub Menu has 2 to 4 options, try and make it part of the Main Menu.
Try and keep Menus under 20 items per menu.

Do you know how many times a day that I create new Folders, or use Find (Files and Folders).
They are the things that I do the most; and both of them require selections from Sub Menus.
Thank you Microsoft!

Grouping techniques:
  - One Long List that can be sorted multiple ways
  - A Menu Tree with only 1 path to an Item
  - Hyper Links, jump point to point, have multiple groupings

That's why Hyper Links are so powerful.  You can jump from anywhere to anywhere, and you can easily create multiple grouping of Links.

Grouping 101
  1) Don't follow Microsoft's lead
  2) Try different ways to group items.  Be creative.
        Then pick the best solution.
  3) When you look at Programs, pay attention to how items are grouped.
        Learn from the experts.  Although some excellent programmers are extremely weak in this area.
        I'm not even close to being an expert programmer;   I need help too (In more ways than one).
                 (Frank, you can say that again - You really do need help)
        As Buzz Light-year said in the movie Toy Story.   "You're a very strange, sad, little person".

One more comment on Menus.  Only a few types of data work well with Menus.  In a lot of cases, menus just don't show you enough choices at one time.  Everything is tucked in tiny cubby holes, and the limbs of the menu tree are not mutually exclusive.

For example, look at all the places that you find Options, Preferences, Configuration, Properties and Setup information.
They can keep the structure that they have now; but, please add an OPTIONS menu, that lists everything in one place.
Even Delphi 3      Project / Options                              Tools / Env.Options                        Tools / ConfigureTools
                           RightClickTools / Properties              RightClickPalette / Properties


 

When I started to learn Delphi, I wanted to see some examples of Form display styles.  I wanted to see some real programs, so that I could get a feel for what looked good, and learn from other people's examples.  Well I am still looking for some good examples.
Books, give you very little help in showing and explaining different display styles and grouping techniques.

It's hard to learn from some Example Programs, because a lot of the programming was done using the ObjectInspector (ObjI).
So, there is very little code or no code at all.
If you are not familiar with a Component, you don't know what all the Properties do (or how to use them).
And what is worse, you do not know the Default values; so that if the programmer changed a Property, you don't know which ones have been changed.

Hey, that would be a nice feature (Pay attention Borland)
  - Mark the Properties (in the ObjI) that have been changed.  That would help beginners a lot.
       or put the changed properties, at the top of the list
  - It could even help the seasoned programmer, get some visual feedback
  - Even having markers on items in the ObjI, depending on their Category and Status

Let me look back, at the errors that I have made writing Delphi programs.
  1) Not naming Components at the start, writing code, then renaming the Component!!
       OOP's, Delphi didn't change the names inside my procedures.
 2) Forgetting to Convert the Var into the right type     IntToStr(  );  ...AsString;
 3) On the Form.  Not using Panels and GroupBoxes enough.
       Now I almost always put a Panel down first, knowing that I will want to group these later.
 4) Not knowing When and How to use different Components.

One point.  Don't forget a pencil and paper when you program.
   1) Keep a folder of 1 or 2 sheet References on (Dates, SQL, Formats, ...)
         a great concise look at all your choices
  2) Shut off the computer, sit back in a comfy chair, and start structuring you program, with a Pencil and Paper.
        One point.  Don't erase much.  If you change a lot of stuff, redo it on another sheet.  Don't erase.
             If you find yourself erasing a lot, then get on the computer, and do your designs there.
        Create a concise map of a task (on 1 sheet).  Yes, put everything on 1 sheet.

With these Lessons, I want to improve both your and my programming  STYLE.
I also want to Group things together for you in different ways.   That's why the best Instructors at school, were the ones that explained things from a different perspective.

How can you learn things faster?
  - Load data into all of your senses See it, Feel it, Say it, Hear it , Touch it
      - have a pencil and paper on your desk.  Make short notes to yourself, write things down.
  - Reinforce good behavior; do the correct thing over and over, get good habits
  - Have quick access to lots of data (this is were seasoned programmers can help newcomers)
  - When you learn it, keep it, and have quick access to it.
       - It is difficult enough to learn Delphi without re-learning things. Learn it once.
  - You learn by doing, creating RR Tracks of strong multi-sensual channels. (sounds pornographic)
  - Your mind is very visual.  Visual images are easier to remember.

 


 

Body Physiology

I read up on Body Physiology a few years ago, and found some fascinating facts:

1) Your Brain only burns 98% Glucose (short chain Carbohydrate - Honey)
2) Your Heart burns 80% Fat and 20% Glucose.

3) Glucose (Honey) is similar to Sucrose (Table Sugar) in all ways
4) Glucose and Sucrose are processed in your Stomach (fast within 15 minutes)
5) Fructose (Fruit Sugar) is similar to Glucose, except Fructose is processed in your Gut (slow - 1 to 2 hours)

6) Glucose leaves ashes (lactic acid) that must be removed by your blood stream
7) Fat burns with no ashes.  Fat turns into CO2 and Water.
       Your Brain burns Glucose because it has a tremendous blood flow system
       Your Heart burns Fat because fat has 2 times the energy density as Glucose,
           and your Heart does not need your blood stream to carry away all the ashes (there are no ashes)

8) For its size, our Brain burns energy 8 times faster than any other muscle.
9) Thinking burns a ton of Glucose.
10) If you are mentally tired, eat Glucose (Honey) or Sucrose (Sugar) for quick a energy boost; that is fast acting (15 min).
        Not long chain Carbohydrates like Bread which take hours to digest.
11) Conclusion:  Even though Sugar is not that good for you; When you are programming, Sugar can improve your mental energy.

 


 

Here's a request that I have for everyone.

New programmers need to see more examples of everything
.
Do you have a Form, Dialog or Panel of Components; that you like and are kind of proud of?
Could you share it with newcomers?
Just email me the .dfm file and .pas file (with your name and no code), so that I can create a Library of Forms.

Do you have an example program, that you learned from?

Thanks


 

Now for some Delphi Stuff:

 


 

Forms, Dialog Boxes, Messages , ...

Trying to lookup (in my Delphi books) all the ways to Display messages to the User; I found that most books did not even list some. Or they were listed in 3 different chapters scattered throughout the book. Or they used them but did not explain their features.  No wonder I had a hard time seeing what all my options were.  No one put them all in the same place.

Ways to Display data to the User in a Form, Window (also called a Dialog Box):

Form2.Show;
        Opens(Shows) Form2 (but allows user to click on Form1)

Form2.ShowModal;
        Opens (Shows) Form2 (but DOES NOT allows user to click on Form1)

ShowMessage('This is a Message');
        Simply Display a line of text; the User has to Hit the OK Button to exit the message window).

    ShowMessage('So this is a Message Box, WOW');

MessageDlg('Msg',mtConfirmation,[mbYes],0);
      Same as ShowMessage but with more Button options for the User to hit.

  if MessageDlg('Please say YES or NO',mtConfirmation,[mbYes,mbNo],0)=mrYES then
  begin
    EntryEB.Text:='You Hit the YES Button';
  end;


 

    TMsgDlgType = mtWarning, mtError, mtInformation, mtConfirmation, mtCustom
    TMsgDlgBtn =  mbYes,    mbNo,    mbOK,    mbCancel,    mbAbort,   mbRetry,   mbIgnore,   mbAll,  mbHelp
    Return values =   mrNone,    mrYes,     mrNo,    mrOk,     mrCancel,     mrAbort,   mrRetry,   mrIgnore,   mrAll


 

InputBox(...);
        Lets the User Enter data (as a Entry String) (CANCEL Button Clears the Entry String to '')

    var
  `   InputString: string;
    begin
      InputString:= InputBox('User Name Entry', 'Please Enter your Name', '');
    end;


 

InputQuery(...);(very similar to InputBox)
        Lets the User Enter data, and returns the Button he hit (OK or CANCEL Button)

  var
    EntryStr: string;
    ClickedOK: Boolean;
  begin
    ClickedOK := InputQuery('User Name Entry', 'Please Enter your Name', EntryStr);
  end;

I wrote a sample program (Windows1P.dpr) in L4Examples.zip that demonstrates all of these window types.

Also, lookup (hit F1) on ShowMessage, MessageDlg, InputBox, InputQuery


 

Forms:

    I usually MAXIMIZE the size (WindowState:=msMaximized)
    That way, I don't have to worry about MODAL Forms, since you cannot click outside a maximized Form.
    For non maximized Forms, I usually make them MODAL
        begin
          Form2.ShowModal;
        end;

 Different ways to Create your Forms:
        1) Let Delphi Create your Forms when the program first runs
        2) Create and Free (Destroy) your Forms as you need them (Dynamically in code)

 1) Delphi automatically creates your Forms.
                Look at the .dpr File for a 2 Form, project.
    {$R *.RES}

    begin
      Application.Initialize;
      Application.CreateForm(TForm1, Form1); // Form1 is Created here
      Application.CreateForm(TForm2, Form2); // Form2 is Created here
      Application.Run;
    end.


 

To stop Delphi from creating your forms like this, you have to go into the:
    -VIEW PROJECT MANAGER (Menu)
        -Select OPTIONS
            -and Move Form2 from the Left Box to the Right Box

Then the .dpr File changes to:


 

  begin
    Application.Initialize;
    Application.CreateForm(TForm1, Form1); // Only Form1 is Created
    Application.Run;
  end.


 

2) Dynamically Creating your Forms in code

  procedure TForm1.ShowF2BtnClick(Sender: TObject);
  begin
    Form2:=TForm2.Create(self); // Create Form2
    Form2.ShowModal;
    Form2.Free;                // Destroy (Free) Form2
  end;


 

What are the Advantages and Disadvantages of Automatic or Dynamic Form Creation?

1) Automatic
    Adv:   -All Forms are created for you at once
              -There is no delay within your program, waiting for Delphi to create forms

    DisAdv:     -Have to wait longer for the program to start, as Forms are created
                     -Uses more memory, to keep Forms created

2) Dynamic
    Adv:   -Uses less memory
              -Program can start quicker

   DisAdv:     -Delays within program, as Forms are created
                    -If you have a Memory Leak in your Forms, then every time you Create and Free each Form, more memory is lost.
 

Frank's Preference:

Unless you have a program with 20+ Large Forms, let Delphi create them automatically. There is no big advantage for Dynamically creating Forms; and some problems (like Memory Leaks) can be amplified if you Create and Free Forms..


 

TypeCasts

var XInt  : integer;
    XByte : byte;
    XChar : char;
    XBoolean : boolean;

XInt:=Integer('A');   // XInt = 65    typecast(char to int)
XByte:=Byte('A');     // XByte = 65   typecast(char to byte)

XBoolean:=Boolean(0); // XBoolean = False

XChar:=char(65);      // XChar = 'A'  typecast(byte to char)

XChar:=chr(65);       // XChar = 'A'  chr( ) is a function
XByte:=ord('A');      // XByte = 65   ord( ) is a function


 

Note:

I was going to try and explain the usage of the MaskEdit Component (which I don't use very much).
So, I started by trying to find examples of MaskEdits in the over 3000 *.pas files that I have from Book CD's etc.

Guess, how many examples that I found?  11
Wow, I would think that more people would want to filter User input.  They do, but not with MaskEdit.

No wonder why I don't use MaskEdits very much.  Nobody does.
What does that say?  Sure enough, MaskEdit is not very versatile and is sometimes difficult to use.
As a reference, I also searched for TEdit Components (in the 3000 *.pas files); and found 523


 

Different way to Group Delphi's most commonly used Components:
 
 

Containers
    Panel     GroupBox     PageControl 
    DBRadioGroup

Navigation:
    ScrollBar        UpDown 
    DBNavigator  TabControl

Non Visible:
  Timer    DataSource 
  Table    Query

Grids
    StringGrid 
    DBGrid

Graphic Comps:
    Shape 
    Image

Data Entry:
    Edit           MaskEdit 
    RichEdit    DBEdit

Selection
    Button          SpeedBtn 
    BitBtn          RadioButton 
    MainMenu   PopupMenu 
    DateTimePicker   TrackBar 
    CheckBox

Display
   Label        StaticText     StatusBar 
   ToolBar    CoolBar 
   Splitter      Chart 
   TreeView   ListView 
   HeaderControl   ProgressBar

Lists
   ListBox        Memo   ComboBox 
   CheckListBox           DBListBox 
   DBMemo         DBComboBox 
   DBCheckBox   DBLookupComboBox 
   DBLookupListBox

That's all for now.

Frank